WP_Query Class is as the name suggests The WordPress Query class.
Mostly we apply direct functions in WordPress files if we are developing a theme. So for a basic theme we hardly deal with advanced level queries and the class internals as well as the global variables.
WordPress has many inbuilt different functions using which we can get the information we need in different files.
Still, there are few scenarios in which we would want to use WP_Query.
The first scenario is to find out what type of request WordPress is currently dealing with.
The $is_* properties are designed to hold this information. We can use the Conditional Tags to interact with that information. In many cases, you would want to interact with this when you’re writing your plugin or a theme.
The second scenario is during The Loop.
WP_Query provides number of functions for many common tasks within The Loop.
For example, when we write have_posts(), it will call $wp_query->have_posts() function and check if there are any posts to show.
If there are posts then we can start a while loop using have_posts() function as the condition. This will iterate around as long as there are posts to show.
In each iteration we can call the_post(), which is going nothing but $wp_query->the_post() function. Calling that function will set up internal variables within $wp_query and the global $post variable.
These are the functions you should use when writing a theme file that needs a loop.
If you use the_post() with your query, you need to run wp_reset_postdata() afterwards to have template tags use the main query’s current post again.
🐛🐛🐛 Also, for querying posts in the admin, consider using get_posts() as wp_reset_postdata() might not behave as expected. Here is more info on the bug.
How to use WP_Query?
We can just use a standard loop.
have_posts() ) {
echo ' ';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '- ' . get_the_title() . '
';
}
echo '
';
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
We can use pagination in a standard loop.
have_posts() ) :
// pagination
while ( $the_query->have_posts() ) : $the_query->the_post();
?>
We can use multiple loops.
have_posts() ) {
$query1->the_post();
echo ' ' . get_the_title() . ' ';
}
wp_reset_postdata();
/* The 2nd Query (without global var) */
$query2 = new WP_Query( $args2 );
// The 2nd Loop
while ( $query2->have_posts() ) {
$query2->the_post();
echo '' . get_the_title( $query2->post->ID ) . ' ';
}
// Restore original Post Data
wp_reset_postdata();
?>
Credit: WordPress
class examples posts query sql sql query WP_Query