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.
You are using a
WP_Query
object, you just don’t know it (yet).WordPress generates a
global
called$wp_query
which isWP_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 likethe_post
,have_posts
, and some others, assume the$wp_query
object. Take a look at the source for one of them:See how the function
the_post
simply grabs theglobal
$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 newWP_Query
you have to use the long form–$my_query->the_post()
You can also follow WordPress Theme Developer Official Handbook
In here you will get the appropriate answer to the WP Loop and Query post.
https://developer.wordpress.org/themes/basics/the-loop/
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 useWP_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: