reference: http://codex.wordpress.org/Function_Reference/query_posts
query_posts() can be used to control which posts show up in The Loop. It accepts a variety of parameters in the same format as used in your URL (e.g. p=4 to show only post of ID number 4).
Why go through all the trouble of changing the query that was meticulously created from your given URL? You can customize the presentation of your blog entries by combining it with page logic (like the Conditional Tags) — all without changing any of the URLs.
Common uses might be to:
The query_posts function is intended to be used to modify the main page Loop only. It is not intended as a means to create secondary Loops on the page. If you want to create separate Loops outside of the main one, you should use get_posts() instead. Use of query_posts on Loops other than the main one can result in your main Loop becoming incorrect and possibly displaying things that you were not expecting.
The query_posts function overrides and replaces the main query for the page. To save your sanity, do not use it for any other purpose.
<?php //The Query query_posts('posts_per_page=5'); //The Loop if ( have_posts() ) : while ( have_posts() ) : the_post(); .. endwhile; else: .. endif; //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). If you want to preserve that information, 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 argument must begin with an ampersand (&).
This is not an exhaustive list yet. It is meant to show some of the more common things possible with setting your own queries.
Show posts only belonging to certain categories.
Show One Category by ID
Display posts from only one category ID (and any children of that category):
query_posts('cat=4');
Show One Category by Name
Display posts from only one category by name:
query_posts('category_name=Staff Home');
Show Several Categories by ID
Display posts from several specific category IDs:
query_posts('cat=2,6,17,38');
Exclude Posts Belonging to Only One Category
Show all posts except those from a category by prefixing its ID with a ‘-’ (minus) sign.
query_posts('cat=-3');
This excludes any post that belongs to category 3.
Multiple Category Handling
Display posts that are in multiple categories. This shows posts that are in both categories 2 and 6:
query_posts(array('category__and' => array(2,6)));
To display posts from either category 2 OR 6, you could use cat as mentioned above, or by using category__in (note this does not show posts from any children of these categories):
query_posts(array('category__in' => array(2,6)));
You can also exclude multiple categories this way:
query_posts(array('category__not_in' => array(2,6)));
Show posts associated with certain tags.
Fetch posts for one tag
query_posts('tag=cooking');
This must use the tag slugs. E.g. query_posts(‘tag=dinner-recipe’); for the tag “dinner recipe”
Fetch posts that have either of these tags
query_posts('tag=bread,baking');
Fetch posts that have all three of these tags:
query_posts('tag=bread+baking+recipe');
Multiple Tag Handling
Display posts that are tagged with both tag id 37 and tag id 47:
query_posts(array('tag__and' => array(37,47)));
To display posts from either tag id 37 or 47, you could use tag as mentioned above, or explicitly specify by using tag__in:
query_posts(array('tag__in' => array(37,47)));
Display posts that do not have any of the two tag ids 37 and 47:
query_posts(array('tag__not_in' => array(37,47)));
The tag_slug__in and tag_slug__and behave much the same, except match against the tag’s slug.
Also see Ryan’s discussion of Tag intersections and unions.
You can also restrict the posts by author.
Note: author_name operates on the user_nicename field, whilst author operates on the author id field.
Display all Pages for author=1, in title order, with no sticky posts tacked to the top:
query_posts('caller_get_posts=1&author=1&post_type=page&post_status=publish&orderby=title&order=ASC');
Retrieve a single post or page.
To return both posts and custom post type movie
query_posts( array( 'post_type' => array('post', 'movie') ) );
Sticky posts first became available with WordPress Version 2.7. Posts that are set as Sticky will be displayed before other posts in a query, unless excluded with the caller_get_posts=1 parameter.
To return just the first sticky post:
$sticky=get_option('sticky_posts') ; query_posts('p=' . $sticky[0]);
or
$args = array( 'posts_per_page' => 1, 'post__in' => get_option('sticky_posts'), 'caller_get_posts' => 1 ); query_posts($args);
Note: the second method returns only the more recent sticky post; if there are not sticky posts, it returns the last post published.
To return just the first sticky post or nothing:
$sticky = get_option('sticky_posts'); $args = array( 'posts_per_page' => 1, 'post__in' => $sticky, 'caller_get_posts' => 1 ); query_posts($args); if($sticky[0]) { // insert here your stuff... }
To exclude all sticky posts from the query:
query_posts(array("post__not_in" =>get_option("sticky_posts")));
Return ALL posts with the category, but don’t show sticky posts at the top. The ‘sticky posts’ will still show in their natural position (e.g. by date):
query_posts('caller_get_posts=1&posts_per_page=3&cat=6');
Return posts with the category, but exclude sticky posts completely, and adhere to paging rules:
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $sticky=get_option('sticky_posts'); $args=array( 'cat'=>3, 'caller_get_posts'=>1, 'post__not_in' => $sticky, 'paged'=>$paged, ); query_posts($args); ?>
Retrieve posts belonging to a certain time period.
Returns posts for just the current date:
$today = getdate(); query_posts('year=' .$today["year"] .'&monthnum=' .$today["mon"] .'&day=' .$today["mday"] );
Returns posts for just the current week:
$week = date('W'); $year = date('Y'); query_posts('year=' . $year .'&w=' .$week );
Returns posts dated December 20:
query_posts( 'monthnum=12&day=20' );
Note: The queries above return posts for a specific date period in history, i.e. “Posts from X year, X month, X day”. They are unable to fetch posts from a timespan relative to the present, so queries like “Posts from the last 30 days” or “Posts from the last year” are not possible with a basic query, and require use of the posts_where filter to be completed. The examples below use the posts_where filter, and should be modifyable for most time-relative queries.
Return posts for posts for March 1 to March 15, 2009:
<?php //Create a new filtering function that will add our where clause to the query function filter_where($where = '') { //posts for March 1 to March 15, 2009 $where .= " AND post_date >= '2009-03-01' AND post_date < '2009-03-16'"; return $where; } // Register the filtering function add_filter('posts_where', 'filter_where'); // Perform the query, the filter will be applied automatically query_posts($query_string); ?>
Return posts from the last 30 days:
<?php //Create a new filtering function that will add our where clause to the query function filter_where($where = '') { //posts in the last 30 days $where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'"; return $where; } // Register the filtering function add_filter('posts_where', 'filter_where'); // Perform the query, the filter will be applied automatically query_posts($query_string); ?>
Return posts 30 to 60 days old
<?php //Create a new filtering function that will add our where clause to the query function filter_where($where = '') { //posts 30 to 60 days old $where .= " AND post_date >= '" . date('Y-m-d', strtotime('-60 days')) . "'" . " AND post_date <= '" . date('Y-m-d', strtotime('-30 days')) . "'"; return $where; } // Register the filtering function add_filter('posts_where', 'filter_where'); // Perform the query, the filter will be applied automatically query_posts($query_string); ?>
You can displace or pass over one or more initial posts which would normally be collected by your query through the use of the offset parameter.
The following will display the 5 posts which follow the most recent (1):
query_posts('posts_per_page=5&offset=1');
Sort retrieved posts by this field.
Designates the ascending or descending order of the ORDERBY parameter.
Retrieve posts (or Pages) based on a custom field key or value.
Returns posts with custom fields matching both a key of ‘color’ AND a value of ‘blue’:
query_posts('meta_key=color&meta_value=blue');
Returns posts with a custom field key of ‘color’, regardless of the custom field value:
query_posts('meta_key=color');
Returns posts where the custom field value is ‘color’, regardless of the custom field key:
query_posts('meta_value=color');
Returns any Page where the custom field value is ‘green’, regardless of the custom field key:
query_posts('post_type=page&meta_value=green');
Returns both posts and Pages with a custom field key of ‘color’ where the custom field value IS NOT EQUAL TO ‘blue’:
query_posts('post_type=any&meta_key=color&meta_compare=!=&meta_value=blue');
Returns posts with custom field key of ‘miles’ with a custom field value that is LESS THAN OR EQUAL TO 22. Note the value 99 will be considered greater than 100 as the data is stored as strings, not numbers.
query_posts('meta_key=miles&meta_compare=<=&meta_value=22');
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));
In 2.3 and 2.5 one would expect the following to return all posts that belong to category 1 and is tagged “apples”
query_posts('cat=1&tag=apples');
A bug prevents this from happening. See Ticket #5433. A workaround is to search for several tags using +
query_posts('cat=1&tag=apples+apples');
This will yield the expected results of the previous query. Note that using ‘cat=1&tag=apples+oranges’ yields expected results.
Placing this code in your index.php file will cause your home page to display posts from all categories except category ID 3.
<?php if (is_home()) { query_posts("cat=-3"); } ?>
You can also add some more categories to the exclude-list (tested with WP 2.1.2):
<?php if (is_home()) { query_posts("cat=-1,-2,-3"); } ?>
To retrieve a particular post, you could use the following:
<?php // retrieve one post with an ID of 5 query_posts('p=5'); ?>
If you want to use the Read More functionality with this query, you will need to set the global $more variable to 0.
<?php // retrieve one post with an ID of 5 query_posts('p=5'); global $more; // set $more to 0 in order to only get the first part of the post $more = 0; // the Loop while (have_posts()) : the_post(); // the content of the post the_content('Read the full post »'); endwhile; ?>
To retrieve a particular page, you could use the following:
<?php query_posts('page_id=7'); //retrieves page 7 only ?>
or
<?php query_posts('pagename=about'); //retrieves the about page only ?>
For child pages, the slug of the parent and the child is required, separated by a slash. For example:
<?php query_posts('pagename=parent/child'); // retrieve the child page of a parent ?>
You can pass a variable to the query with two methods, depending on your needs. As with other examples, place these above your Loop:
In this example, we concatenate the query before running it. First assign the variable, then concatenate and then run it. Here we’re pulling in a category variable from elsewhere.
<?php $categoryvariable=$cat; // assign the variable as current category $query= 'cat=' . $categoryvariable. '&orderby=date&order=ASC'; // concatenate the query query_posts($query); // run the query ?>
In this next example, the double quotes tell PHP to treat the enclosed as an expression. For this example, we are getting the current month and the current year, and telling query_posts to bring us the posts for the current month/year, and in this case, listing in ascending order so we get the oldest post at the top of the page.
<?php $current_month = date('m'); $current_year = date('Y'); query_posts("cat=22&year=$current_year&monthnum=$current_month&order=ASC"); ?> <!-- put your loop here -->
This example explains how to generate a complete list of posts, dealing with pagination. We can use the default $query_string telling query_posts to bring us a full posts listing. We can also modify the posts_per_page query argument from -1 to the number of posts you want to show on each page; in this last case, you’ll probably want to use posts_nav_link() to navigate the generated archive.
<?php query_posts($query_string.'&posts_per_page=-1'); while(have_posts()) { the_post(); <!-- put your loop here --> } ?>
If you don’t need to use the $query_string variable, another method exists that is more clear and readable, in some more complex cases. This method puts the parameters into an array. The same query as in Example 2 above could be done like this:
query_posts(array( 'cat' => 22, 'year' => $current_year, 'monthnum' => $current_month, 'order' => 'ASC', ));
As you can see, with this approach, every variable can be put on its own line, for easier reading.
By default running query_posts will completely overwrite all existing query variables on the current page. Pagination, categories dates etc. will be lost and only the variables you pass into query_posts will be used.
If you want to preserve the original query you can merge the original query array into your parameter array:
global $wp_query; query_posts( array_merge( array('cat' => 1), $wp_query->query ) );
The “Blog pages show at most” parameter in Settings > Reading can influence your results. To overcome this, add the ‘posts_per_page’ parameter. For example:
query_posts('category_name=The Category Name&posts_per_page=-1'); //returns ALL from the category