query_posts() WordPress Function
The query_posts() function is a way to modify the main query that WordPress uses to display posts on a page. This function can be used within the loop to make changes to how many posts are displayed, or it can be used outside the loop to alter the main query before it is run.
query_posts( array|string $query ) #
Sets up The Loop with query parameters.
Contents
Description
Note: This function will completely override the main query and isn’t intended for use by plugins or themes. Its overly-simplistic approach to modifying the main query can be problematic and should be avoided wherever possible. In most cases, there are better, more performant options for modifying the main query such as via the ‘pre_get_posts’ action within WP_Query.
This must not be used within the WordPress Loop.
Parameters
- $query
(array|string)(Required)Array or string of WP_Query arguments.
Return
(WP_Post[]|int[]) Array of post objects or post IDs.
More Information
query_posts() is a way to alter the main query that WordPress uses to display posts. It does this by putting the main query to one side, and replacing it with a new query. To clean up after a call to query_posts, make a call to wp_reset_query(), and the original main query will be restored.
It should be noted that using this to replace the main query on a page can increase page loading times, in worst case scenarios more than doubling the amount of work needed or more. While easy to use, the function is also prone to confusion and problems later on. See the note further below on caveats for details.
For general post queries, use WP_Query or get_posts().
It is strongly recommended that you use the ‘pre_get_posts’ action instead, and alter the main query by checking is_main_query().
For example, on the homepage, you would normally see the latest 10 posts. If you want to show only 5 posts (and don’t care about pagination), you can use query_posts() like so:
query_posts( 'posts_per_page=5' );
Here is similar code using the ‘pre_get_posts’ action in functions.php :
function wpdocs_five_posts_on_homepage( $query ) { if ( $query->is_home() && $query->is_main_query() ) { $query->set( 'posts_per_page', 5 ); } } add_action( 'pre_get_posts', 'wpdocs_five_posts_on_homepage' );
Usage
// The Query query_posts( $args ); // The Loop while ( have_posts() ) : the_post(); echo ' <li>'; the_title(); echo '</li> '; endwhile; // Reset Query wp_reset_query();
Place a call to query_posts() in one of your Template files before The Loop begins. The WP_Query object will generate a new SQL query using your parameters. When you do this, WordPress ignores the other parameters it receives via the URL (such as page number or category).
Preserving Existing Query Parameters
If you want to preserve the original query parameter information that was used to generate the current query, and then add or over-ride some parameters, you can use the $query_string global variable in the call to query_posts().
For example, to set the display order of the posts without affecting the rest of the query string, you could place the following before The Loop:
global $query_string; query_posts( $query_string . '&order=ASC' );
When using query_posts() in this way, the quoted portion of the parameter must begin with an ampersand (&).
Or alternatively, you can merge the original query array into your parameter array:
global $wp_query; $args = array_merge( $wp_query->query_vars, array( 'post_type' => 'product' ) ); query_posts( $args );
Combining Parameters
You may have noticed from some of the examples above that you combine parameters with an ampersand (&), like so:
query_posts( 'cat=3&year=2004' );
Posts for category 13, for the current month on the main page:
if ( is_home() ) { query_posts( $query_string . '&cat=13&monthnum=' . date( 'n', current_time( 'timestamp' ) ) ); }
At 2.3 this combination will return posts belong to both Category 1 AND 3, showing just two (2) posts, in descending order by the title:
query_posts( array( 'category__and' => array(1,3), 'posts_per_page' => 2, 'orderby' => 'title', 'order' => 'DESC' ) );
The following returns all posts that belong to category 1 and are tagged “apples”.
query_posts( 'cat=1&tag=apples' );
You can search for several tags using “+”. In this case, all posts belong to category 1 and tagged as “apples” and “oranges” are returned.
query_posts( 'cat=1&tag=apples+oranges' );
Caveats
query_posts() is only one way amongst many to query the database and generate a list of posts. Before deciding to use query_posts(), be sure to understand the drawbacks.
Alters Main Loop
query_posts() is meant for altering the main loop. It does so by replacing the query used to generate the main loop content. Once you use query_posts(), your post-related global variables and template tags will be altered. Conditional tags that are called after you call query_posts() will also be altered – this may or may not be the intended result.
Secondary Loops
To create secondary listings (for example, a list of related posts at the bottom of the page, or a list of links in a sidebar widget), try making a new instance of WP_Query or use get_posts().
If you must use query_posts(), make sure you call wp_reset_query() after you’re done.
Pagination
Pagination won’t work correctly, unless you set the ‘paged’ query var appropriately: adding the paged parameter
Additional SQL Queries
If you use query_posts within a template page, WordPress will have already executed the database query and retrieved the records by the time it gets to your template page (that’s how it knew which template page to serve up!). So when you over-ride the default query with query_posts(), you’re essentially throwing away the default query and its results and re-executing another query against the database.
This is not necessarily a problem, especially if you’re dealing with a smaller blog-based site. Developers of large sites with big databases and heavy visitor traffic may wish to consider alternatives, such as modifying the default request directly (before it’s called). The ‘request’ filter can be used to achieve exactly this.
The ‘parse_query’ and the ‘pre_get_posts’ filters are also available to modify the internal $query
object that is used to generate the SQL to query the database.
Resources
- For more in-depth discussion of how WordPress generates and handles its queries, review these articles: Query Overview and Custom Queries
- Customize the Default Query properly using ‘pre_get_posts’ – Bill Erickson – Customize the WordPress Query or John James Jacoby – Querying Posts Without query_posts
- You don’t know Query – Slides from WordCamp Netherlands 2012 by Andrew Nacin
Source
File: wp-includes/query.php
function query_posts( $query ) { $GLOBALS['wp_query'] = new WP_Query(); return $GLOBALS['wp_query']->query( $query ); }
Expand full source codeCollapse full source codeView on TracView on GitHub
Changelog
Version | Description |
---|---|
1.5.0 | Introduced. |