Skip to content

Instantly share code, notes, and snippets.

@tomjn
Created May 27, 2020 10:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tomjn/3e7e943f91b629325f0ec6a27922d3ca to your computer and use it in GitHub Desktop.
Save tomjn/3e7e943f91b629325f0ec6a27922d3ca to your computer and use it in GitHub Desktop.
A standard WP_Query loop
<?php
$args = [
// parameters go here
];
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// display the post
the_title();
the_content();
}
wp_reset_postdata();
} else {
echo "no posts were found";
}
@tomjn
Copy link
Author

tomjn commented Oct 2, 2020

Note that these two loop are the same in a very literal sense:

if ( have_posts() ) {
	while ( have_posts() ) {
		the_post();
		// display the post
		the_title();
		the_content();
	}
} else {
	echo "no posts were found";
}

global $wp_query;
if ( $wp_query->have_posts() ) {
	while ( $wp_query->have_posts() ) {
		$wp_query->the_post();
		// display the post
		the_title();
		the_content();
	}
} else {
	echo "no posts were found";
}

have_posts() and the_post() are just wrappers around $wp_query->have_posts() and $wp_query->the_post()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment