Skip to content

Instantly share code, notes, and snippets.

@chrisjangl
Last active June 22, 2020 15:17
Show Gist options
  • Save chrisjangl/4fa94194da5f4ba371b061ee5f3c9a35 to your computer and use it in GitHub Desktop.
Save chrisjangl/4fa94194da5f4ba371b061ee5f3c9a35 to your computer and use it in GitHub Desktop.
Create a custom WP_Query, and loop through the results, making sure to reset the query afterward
<?php
/**
* create a custom query, using specific arguments, making sure to reset
* the query afterward.
*/
function create_secondary_query() {
// for list of possible arguments, @see https://developer.wordpress.org/reference/classes/wp_query/#parameters
$args = array(
'posts_per_page' => 3 , // how many posts to return?
);
ob_start();
$secondary_query = new WP_Query( $args );
if ( $secondary_query->have_posts() ):
while ( $secondary_query->have_posts() ):
$secondary_query->the_post(); ?>
<?php
// do something with each post here ?>
<?php
// end while $secondary_query->have_posts():
endwhile;
// end if $secondary_query->have_posts():
endif;
return ob_get_clean();
wp_reset_query();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment