WordPress 中文文档
Template Tags/query posts
出自WordPress Chinese 中文文档
目录 |
Description
ttQuery_posts/tt 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. ttp=4/tt 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:
- Display only a single post on your homepage (a single Page can be done via Settings - Reading).
- Show all posts from a particular time period.
- Show the latest post (only) on the front page.
- Change how posts are ordered.
- Show posts from only one category.
- Exclude one or more categories.
Important note
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 create separate WP_Query objects and use those 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.
Usage
Place a call to ttquery_posts()/tt in one of your Template files before The Loop begins. The ttwp_query/tt 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 variable tt$query_string/tt in the call to ttquery_posts()/tt.
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:
ttquery_posts($query_string . order=ASC)/tt
When using ttquery_posts/tt in this way, the quoted portion of the argument must begin with an ampersand ().
Examples
Exclude Categories From Your Home Page
Placing this code in your ttindex.php/tt file will cause your home page to display posts from all categories except category ID 3.
pre ?php
if (is_home()) {
query_posts(cat=-3);
}
? /pre
You can also add some more categories to the exclude-list(tested with WP 2.1.2):
pre ?php
if (is_home()) {
query_posts(cat=-1,-2,-3);
}
? /pre
Retrieve a Particular Post
To retrieve a particular post, you could use the following:
pre ?php // retrieve one post with an ID of 5 query_posts('p=5'); ? /pre
If you want to use the Read More functionality with this query, you will need to set the global $more variable to 0.
pre ?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 raquo;');
endwhile; ? /pre
Retrieve a Particular Page
To retrieve a particular page, you could use the following:
pre ?php query_posts('page_id=7'); //retrieves page 7 only ? /pre or pre ?php query_posts('pagename=about'); //retrieves the about page only ? /pre
For child pages, the slug of the parent and the child is required, separated by a slash. For example:
pre ?php query_posts('pagename=parent/child'); // retrieve the child page of a parent ? /pre
Passing variables to query_posts
You can pass a variable to the query with two methods, depending on your needs. As with other examples, place these above your Loop:
Example 1
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.
pre
?php $categoryvariable=$cat; // assign the variable as current category $query= 'cat=' . $categoryvariable. 'orderby=dateorder=ASC'; // concatenate the query query_posts($query); // run the query ?
/pre
Example 2
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 so we get oldest post at top of page. pre
?php $current_month = date('m'); ? ?php $current_year = date('Y'); ?
?php query_posts(cat=22year=$current_yearmonthnum=$current_monthorder=ASC); ? !-- put your loop here -- /pre
Example 3
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. . pre ?php query_posts($query_string.'posts_per_page=-1'); while(have_posts()) { the_post(); !-- put your loop here -- } ? /pre
Example 4
If you don't need to use the $query_string variable, then another method exists that is more clear and readable, in some more complex cases. This method puts the parameters into an array, and then passes the array. The same query as in Example 2 above could be done like this:
pre query_posts(array( 'cat' = 22, 'year'= $current_year, 'monthnum'=$current_month, 'order'='ASC', )); /pre
As you can see, with this approach, every variable can be put on its own line, for simpler reading.
Parameters
This is not an exhaustive list yet. It is meant to show some of the more common things possible with setting your own queries.
Category Parameters
Show posts only belonging to certain categories.
- ttcat/tt
- ttcategory_name/tt
- ttcategory__and/tt
- ttcategory__in/tt
- ttcategory__not_in/tt
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. !--There is a proviso however: it will exclude all the posts that belong only to category 3. If a post belongs to another category as well, it will still be picked up.--
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:
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)));
Tag Parameters
Show posts associated with certain tags.
- tttag/tt
- tttag__and/tt
- tttag__in/tt
- tttag_slug__and/tt
- tttag_slug__in/tt
Fetch posts for one tag
query_posts('tag=cooking');
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 in multiple tags:
query_posts(array('tag__and' = array('bread','baking'));
This only shows posts that are in both tags 'bread' and 'baking'. To display posts from either tag, you could use tag as mentioned above, or explicitly specify by using tag__in:
query_posts(array('tag__in' = array('bread','baking'));
The tag_slug__in and tag_slug__and behave much the same, except match against the tag's slug instead of the tag itself.
Also see Ryan's discussion of Tag intersections and unions.
Author Parameters
You can also restrict the posts by author.
- ttauthor_name=Harriet/tt Note: ttauthor_name/tt operates on the ttuser_nicename/tt field, whilst ttauthor/tt operates on the author id.
- ttauthor=3/tt
Display all Pages for author=1, in title order, with no sticky posts tacked to the top:
query_posts('caller_get_posts=1author=1post_type=pagepost_status=publishorderby=titleorder=ASC');
Post Page Parameters
Retrieve a single post or page.
- ttp=27/tt - use the post ID to show that post
- ttname=about-my-life/tt - query for a particular post that has this Post Slug
- ttpage_id=7/tt - query for just Page ID 7
- ttpagename=about/tt - note that this is not the page's title, but the page's path
- ttshowposts=1/tt - use ttshowposts=3/tt to show 3 posts. Use ttshowposts=-1/tt to show all posts
- tt'post__in' = array(5,12,2,14,7)/tt - inclusion, lets you specify the post IDs to retrieve
- tt'post__not_in' = array(6,2,8)/tt - exclusion, lets you specify the post IDs NOT to retrieve
- tt'post_type=page'/tt - returns Pages; defaults to value of post; can be any, attachment, page, or post.
Sticky Post Parameters
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.
- ttarray('post__in'=get_option('sticky_posts'))/tt - returns array of all sticky posts
- ttcaller_get_posts=1/tt - To exclude sticky posts be included at the beginning of posts returned, but the sticky post will still be returned in the natural order of that list of posts returned.
To return just the first sticky post:
$sticky=get_option('sticky_posts') ;
query_posts('p=' . $sticky[0]);
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=1showposts=3cat=6');
Return posts with the category, but exclude sticky posts completely, and adhere to paging rules: pre ?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); ? /pre
Time Parameters
Retrieve posts belonging to a certain time period.
- tthour=/tt - hour (from 0 to 23)
- ttminute=/tt - minute (from 0 to 60)
- ttsecond=/tt - second (0 to 60)
- ttday=/tt - day of the month (from 1 to 31)
- ttmonthnum=/tt - month number (from 1 to 12)
- ttyear=/tt - 4 digit year (e.g. 2009)
- ttw=/tt - week of the year (from 0 to 53) and uses the MySQL WEEK command Mode=1.
Returns posts for just the current date:
$today = getdate();
query_posts('year=' .$today[year] .'monthnum=' .$today[mon] .'day=' .$today[mday] );
Returns posts dated December 20:
query_posts(monthnum=12day=20' );
Page Parameters
- ttpaged=2/tt - show the posts that would normally show up just on page 2 when using the Older Entries link.
- ttposts_per_page=10/tt - number of posts to show per page; a value of -1 will show all posts.
- ttorder=ASC/tt - show posts in chronological order, DESC to show in reverse order (the default)
Offset Parameter
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('showposts=5offset=1');
Orderby Parameters
Sort retrieved posts by this field.
- ttorderby=author/tt
- ttorderby=date/tt
- ttorderby=category/tt Note: this doesn't work and likely will be discontinued with version 2.8
- ttorderby=title/tt
- ttorderby=modified/tt
- ttorderby=menu_order/tt
- ttorderby=parent/tt
- ttorderby=ID/tt
- ttorderby=rand/tt
- ttorderby=meta_value/tt - note that a ttmeta_key=some value/tt clause should be present in the query parameter also
Also consider order parameter of ASC or DESC
Custom Field Parameters
Retrieve posts (or Pages) based on a custom field key or value.
- ttmeta_key=/tt
- ttmeta_value=/tt
- ttmeta_compare=/tt - operator to test the ttmeta_value=/tt, default is '=', with other possible values of '!=', , '=', , or '='
Returns posts with custom fields matching both a key of 'color' AND a value of 'blue':
query_posts('meta_key=colormeta_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=pagemeta_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=anymeta_key=colormeta_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 store as strings, not numbers.
query_posts('meta_key=milesmeta_compare==meta_value=22');
Combining Parameters
You may have noticed from some of the examples above that you combine parameters with an ampersand (), like so:
query_posts('cat=3year=2004');
Posts for category 13, for the current month on the main page:
if (is_home()) {
query_posts($query_string . 'cat=13monthnum=' . 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),'showposts'=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=1tag=apples');
A bug prevents this from happening. See Ticket #5433. A workaround is to search for several tags using +
query_posts('cat=1tag=apples+apples');
This will yield the expected results of the previous query. Note that using 'cat=1tag=apples+oranges' yields expected results.
Resources
- If..Else - Query Post Redux
- If..Else - Make WordPress Show Only one Post on the Front Page
- If..Else - Query Posts
- Perishable Press - 6 Ways to Customize WordPress Post Order
- nietoperzka's Custom order of posts on the main page
- http://www.darrenhoyt.com/2008/06/11/displaying-related-category-and-author-content-in-wordpress/ Displaying related category and author content]
- Exclude posts from displaying
!--We need resources from other sources for this article--
Related
bloginfo, bloginfo_rss, get_bloginfo, get_bloginfo_rss, wp_title, wp_get_archives, get_calendar, get_posts, wp_list_pages, wp_page_menu, wp_dropdown_pages, wp_loginout, wp_register, wp_logout_url, query_posts, rss_enclosure
div style=background: #f7f7f7; border: 1px solid #000; padding: 10px;
How to pass parameters to tags
div style=background: #fee; border: 1px dotted #c66; margin: 1em 0; padding: 1em 0; text-align: center;This page is marked as incomplete. You can help Codex by expanding it./div

