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.

4 Answers
4

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()

Leave a Comment