WP_Query
for secondary requests and queries.pre_get_posts
.query_posts
and wp_reset_query
at all costs.WP_Query
object.WP_Query
codex entry.get_posts
always specify suppress_filters
and use the value false
, so that caches get used. If you do not set this, there will be a performance penalty. This is not needed for WP_Query
.WP_Query
object.WP_Query
( best )get_posts
( okay )query_posts
( avoid at all costs )WP_Query
WP_Query
objects. A WP_Query
object represents a query, e.g. the main query, and has helpful methods such as:have_posts();
and the_post();
found in most themes are wrappers around the main query object:get_posts
get_posts
is similar to WP_Query
, and takes the same arguments, but it returns an array containing the requested posts in full. You shouldn't use get_posts
if you're intending to create a post loop.get_posts
is conceptually simpler than WP_Query
for novice programmers to understand, it does have a downside. get_posts
doesn't make extensive use of the object cache in the way that WP_Query
does, and may not be as performant.suppress_filters
as false
. By default, get_posts
ignores cache, and will run slower.query_posts
query_posts
is an overly simplistic and problematic way to modify the main query of a page by replacing it with new instance of the query.pre_get_posts
hook, for this purpose. Do not use query_posts()
.NOT IN
Querieswp_reset_postdata
WP_Query
or get_posts
, you may set the current post object, using the_post
or setup_postdata
. If you do, you need to clean up after yourself when you finish your while loop. Do this by calling wp_reset_postdata
.wp_reset_postdata
after the if statement. This is incorrect, as the post hasn't changed if the if statement is false, leading to potentially unexpected behavior. Always call the function before the closing brace, not after, e.g.wp_reset_query
query_posts
, you will need to restore the main query after you've done your work. Failure to do so can lead to a large number of issues and unexpected behavior. You can do this with wp_reset_query
. Always do this after calling query_posts
, and only do it when necessary. This means you should never need to use this function.pre_get_posts
Filterpre_get_posts
filter.functions.php
, or in a plugin.