Created
October 16, 2017 17:55
-
-
Save jacobwise/9f9911777a44714f852393896b5b7dd5 to your computer and use it in GitHub Desktop.
A sample controller for a WP_Query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function prefix_get_post_type () { | |
$args = array( | |
'post_type' => 'post_type', | |
'posts_per_page' => 10 | |
); | |
// The Query | |
$the_query = new WP_Query( $args ); | |
// Create empty posts array | |
$posts = array(); | |
// The Loop | |
if ( $the_query->have_posts() ) { | |
while ( $the_query->have_posts() ) { | |
$the_query->the_post(); | |
// Create new posts object | |
$item = new stdClass(); | |
// Set the properties we want on the item | |
$item->id = get_the_ID(); | |
$item->title = get_the_title(); | |
$item->content = get_the_content(); | |
$item->excerpt = get_the_excerpt(); | |
$item->link = get_permalink(); | |
$item->date = get_the_date('m.d.Y'); | |
$item->image = get_the_post_thumbnail_url(get_the_ID(),'thumbnail'); | |
$item->exampleField = get_field('example_field'); | |
// Push item to posts array | |
array_push($posts, $item); | |
} | |
// Restore original Post Data | |
wp_reset_postdata(); | |
} else { | |
// no posts found | |
} | |
// Print posts array to javascript for use in Vue | |
$reshuffled_data = array( | |
'l10n_print_after' => 'posts = ' . json_encode( $posts ) | |
); | |
// Localize this to a script that exists on the page you are loading the controller | |
wp_localize_script( 'vue', 'posts', $reshuffled_data ); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment