Explanation of WP_Query

Why am I able to use WP_Query methods without using an object of this class? Sometimes I see examples that are using the object:

// The Query
$the_query = new WP_Query( $args );

// The Loop
    while ( $the_query->have_posts() ) {
    $the_query->the_post();
    echo '<li>' . get_the_title() . '</li>';
}

But sometimes I don’t use it. I just use the_post(), etc without using a WP_Query object.

Solutions Collecting From Web of "Explanation of WP_Query"

You are using a WP_Query object, you just don’t know it (yet).

WordPress generates a global called $wp_query which is WP_Query object. This object is what is responsible for what is called the “main Loop” colloquially. This $wp_query object is present on every page that I am aware of. Functions like the_post, have_posts, and some others, assume the $wp_query object. Take a look at the source for one of them:

775 /**
776  * Iterate the post index in the loop.
777  *
778  * @see WP_Query::the_post()
779  * @since 1.5.0
780  * @uses $wp_query
781  */
782 function the_post() {
783         global $wp_query;
784 
785         $wp_query->the_post();
786 }

See how the function the_post simply grabs the global $wp_query object and then runs $wp_query->the_post exactly as happens when you created your own object.

It just so happens that there are functions matching the method names of some of the WP_Query object. Those are shortcuts to $wp_query and you can’t use them unless you intend to use $wp_query. That is why when you create a new WP_Query you have to use the long form– $my_query->the_post()

Every request for a WordPress page (a page, a post, a category archive, a tag archive, etc.) generates a main query, which is stored in the global variable $wp_query. When you use WP_Query methods without specifying a query object, WordPress uses this global query object. This main query happens before the template is loaded, and the results of that query is how WordPress determines what template to load.

What you have in your example code is a custom query, separate from the main query. This is used to create queries for additional data aside from the main query. For example, if you want a sidebar with a list of “latest posts” on each page, this would use an additional query. To output that custom query’s data, you have to reference the object that you assigned the data to when you made the query.

You use a new object if you want to keep the main query but want to handle a separate query in the same page. From The Loop Codex examples:

If you need to keep the original query around, you can create a new query object.

<?php $my_query = new WP_Query('category_name=special_cat&posts_per_page=10'); ?>

<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>