Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@tomjn 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