1

This may be a very basic question, but I could not find the answer. The following documentation http://codex.wordpress.org/Class_Reference/WP_Query shows the code

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

but when I look at wp-contents/themese/twentytwelve/index.php I see calls to have_posts() and the_post() inside the loop with no reference to $the_query as though index.php was included from inside a WP_Query instance. Can someone please explain what is happening here?

Thanks.

1
0

You have to read the documentation thoroughly, for example:

The second is during The Loop. WP_Query provides numerous functions for common tasks within The Loop. To begin with, have_posts(), which calls $wp_query->have_posts(), is called to see if there are any posts to show. If there are, a while loop is begun, using have_posts() as the condition. This will iterate around as long as there are posts to show. In each iteration, the_post(), which calls $wp_query->the_post() is called, setting up internal variables within $wp_query and the global $post variable (which the Template Tags rely on), as above. These are the functions you should use when writing a theme file that needs a loop. See also The Loop and The Loop in Action for more information.

Section: WP_Query - Interacting with WP_Query

And to confirm it look up the source code of have_posts():

739 /**
740  * Whether current WordPress query has results to loop over.
741  *
742  * @see WP_Query::have_posts()
743  * @since 1.5.0
744  * @uses $wp_query
745  *
746  * @return bool
747  */
748 function have_posts() {
749         global $wp_query;
750 
751         return $wp_query->have_posts();
752 }

Now you can be sure, the main query does work with the global variable $wp_query.

But you really just have to actually read the documentation and start reading some code, than this wouldn't actually be a question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.