WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

zh-cn:Class Reference/WP Query

描述

WP_Query 是定义于 wp-includes/query.php 中的一个用于处理复杂的请求wordpress博客中文章或页面的类。 wp-blog-header.php (或在wp版本Version 2.0中的类) 提供了 $wp_query 对象定义当前请求的信息, 然后 $wp_query 决定其属于哪种类型的查询(可能是一个分类存档、日期存档、feed或搜索)并获取所请求的文章。它在请求中保留的众多信息可在稍后使用。

与WP_Query的互动

多数情况下,你不用通过处理内部类或全局变量就能找到你所需要的信息。当需要某些信息的时候,这里的众多函数即可供你调用。

WP_Query通常用于这两种情况。 第一种是获取当前WordPress正在处理的请求类型。利用$is_*属性并结合Conditional Tags就可以保存这些数据信息。这是插件作者们经常遇到的情况(也是主题作者第二常见的)。

第二种情况用于The LoopWP_Query 为主循环中的常见任务提供了众多函数。 首先, have_posts()通过$wp_query->have_posts()的形式进行调用,以查询是否有文章。若有,则利用 have_posts() 作为判断条件开始 while 循环。只要有文章要显示就不断地迭代该操作。 如前所述,在每一次迭代的时候, the_post()函数会建立内部变量$wp_query和全局变量$post(依赖于Template Tags ),以 $wp_query->the_post() 的形式调用。写主循环的时候你应该会用上这些函数。可参考 The LoopThe Loop in Action 获得更多信息。

Note: 如果你的查询操作中使用了 the_post(), 你应该调用 wp_reset_postdata() 使得之后的 Template Tags 能再次对当前文章进行查询操作。

用法

<?php

// 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>';
endwhile;

/* Restore original Post Data 
 * NB: Because we are using new WP_Query we aren't stomping on the 
 * original $wp_query and it does not need to be reset.
*/
wp_reset_postdata();


/* The 2nd Query (without global var) */
$query2 = new WP_Query( $args2 );

// The 2nd Loop
while( $query2->have_posts() ):
	$query2->next_post();
	echo '<li>' . get_the_title( $query2->post->ID ) . '</li>';
endwhile;

// Restore original Post Data
wp_reset_postdata();

?>

方法和属性

This is the formal documentation of WP_Query. You shouldn't alter the properties directly, but instead use the methods to interact with them. Also see Interacting with WP_Query for some useful functions that avoid the need to mess around with class internals and global variables.

属性

$query
Holds the query string that was passed to the $wp_query object by WP class.
$query_vars
An associative array containing the dissected $query: an array of the query variables and their respective values.
$queried_object
Applicable if the request is a category, author, permalink or Page. Holds information on the requested category, author, post or Page.
$queried_object_id
If the request is a category, author, permalink or post / page, holds the corresponding ID.
$posts
Gets filled with the requested posts from the database.
$post_count
The number of posts being displayed.
$found_posts
The total number of posts found matching the current query parameters
$max_num_pages
The total number of pages. Is the result of $found_posts / $posts_per_page
$current_post
(available during The Loop) Index of the post currently being displayed.
$post
(available during The Loop) The post currently being displayed.
$is_single, $is_page, $is_archive, $is_preview, $is_date, $is_year, $is_month, $is_time, $is_author, $is_category, $is_tag, $is_tax, $is_search, $is_feed, $is_comment_feed, $is_trackback, $is_home, $is_404, $is_comments_popup, $is_admin, $is_attachment, $is_singular, $is_robots, $is_posts_page, $is_paged
Booleans dictating what type of request this is. For example, the first three represent 'is it a permalink?', 'is it a Page?', 'is it any type of archive page?', respectively.

方法

(An ampersand (&) before a method name indicates it returns by reference.)

init()
Initialise the object, set all properties to null, zero or false.
parse_query( $query )
Takes a query string defining the request, parses it and populates all properties apart from $posts, $post_count, $post and $current_post.
parse_query_vars()
Reparse the old query string.
get( $query_var )
Get a named query variable.
set( $query_var, $value )
Set a named query variable to a specific value.
&get_posts()
Fetch and return the requested posts from the database. Also populate $posts and $post_count.
next_post()
(to be used when in The Loop) Advance onto the next post in $posts. Increment $current_post and set $post to the (new) current post object (note: this does not set the global $post variable, only the WP_Query object's instance variable.) Returns the current post object
the_post()
(to be used when in The Loop) Advance onto the next post, and set the global $post variable.
have_posts()
(to be used when in The Loop, or just before The Loop) Determine if we have posts remaining to be displayed.
rewind_posts()
Reset $current_post and $post.
&query( $query )
Call parse_query() and get_posts(). Return the results of get_posts().
get_queried_object()
Set $queried_object if it's not already set and return it.
get_queried_object_id()
Set $queried_object_id if it's not already set and return it.
WP_Query( $query = '' ) (constructor)
If you provide a query string, call query() with it.

参数

作者

显示某个作者的文章.

  • author (int) - 使用作者 id.
  • author_name (string) - 使用 'user_nicename' (不是名称).

显示某作者的文章

显示某作者的文章, 使用作者 id:

$query = new WP_Query( 'author=123' );

显示某作者的文章, 使用作者的 'user_nicename':

$query = new WP_Query( 'author_name=rami' );

显示几个作者的文章

显示几个指定作者的文章:

$query = new WP_Query( 'author=2,6,17,38' );

排除某个作者的文章

显示所有文章 除了 某个作者的,在作者ID前面加一个 '-' (减号) 就可以了:

$query = new WP_Query( 'author=-12' );

分类目录

显示属于分类目录的文章

  • cat (int) - 使用分类目录 id.
  • category_name (string) - 使用分类目录别名 (不是名称).
  • category__and (array) - 使用分类目录 id.
  • category__in (array) - 使用分类目录 id.
  • category__not_in (array) - 使用分类目录 id.

显示某个分类目录的文章

显示属于这个分类目录的文章 (包含这个分类目录的子分类), 使用分类目录 id:

$query = new WP_Query( 'cat=4' );

显示属于这个分类目录的文章 (包含这个分类目录的子分类), 使用分类目录别名:

$query = new WP_Query( 'category_name=staff' );

显示属于这个分类目录的文章 (包含这个分类目录的子分类), 使用分类目录 id:

$query = new WP_Query( 'category__in=4' );

显示某几个分类目录的文章

显示属于这几分类目录的文章, 使用分类目录 id:

$query = new WP_Query( 'cat=2,6,17,38' );

显示属于这几分类目录的文章, 使用分类目录别名:

$query = new WP_Query( 'category_name=staff,news' );

排除某个分类目录的文章

显示所有文章除了 属于带 '-' (减号) 的几个分类目录.

$query = new WP_Query( 'cat=-12,-34,-56' );

多个分类目录处理

显示同时属于多个分类目录的文章. 下面的查询显示同时输入分类2和6的文章:

$query = new WP_Query( array( 'category__and' => array( 2, 6 ) ) );

需要显示属于分类 2 或 6 的文章, 你可以使上面提到的 cat, 或使用 category__in (这个不显示属于指定分类的子分类的文章):

$query = new WP_Query( array( 'category__in' => array( 2, 6 ) ) );

同时,你可以可以排除同时不属于某些分类的文章:

$query = new WP_Query( array( 'category__not_in' => array( 2, 6 ) ) );

标签

显示包含指定标签的文章.

  • tag (string) - 使用标签别名.
  • tag_id (int) - 使用标签 id.
  • tag__and (array) - 使用标签 ids.
  • tag__in (array) - 使用标签 ids.
  • tag__not_in (array) - 使用标签 ids.
  • tag_slug__and (array) - 使用标签别名.
  • tag_slug__in (array) - 使用标签别名.

显示包含一个标签的文章

显示包含某个标签的文章, 使用标签别名:

$query = new WP_Query( 'tag=cooking' );

显示包含某个标签的文章, 使用标签id:

$query = new WP_Query( 'tag_id=13' );

显示包含某些标签中任意一个标签的文章

$query = new WP_Query( 'tag=bread,baking' );

显示包含 "所有" 指定标签的文章:

$query = new WP_Query( 'tag=bread+baking+recipe' );

多标签处理

显示同时包含标签id 37和47的文章

$query = new WP_Query( array( 'tag__and' => array( 37, 47 ) ) );

显示包含标签id37或47的文章,你可以使用上面提到的tag,或使用tag__in明确指定:

$query = new WP_Query( array( 'tag__in' => array( 37, 47 ) ) );

显示同时不包含标签id 37和47:的文章:

$query = new WP_Query( array( 'tag__not_in' => array( 37, 47 ) ) );

tag_slug__intag_slug__and 的作用是一样的, 不同的是值为标签的别名而不是id。

自定义分类法

显示属于某个自定义分类法的文章。

  • {tax} (string) - use taxonomy slug. Deprecated as of Version 3.1 in favor of 'tax_query'.
  • tax_query (array) - use taxonomy parameters (available with Version 3.1).
    • taxonomy (string) - Taxonomy.
    • field (string) - Select taxonomy term by ('id' or 'slug')
    • terms (int/string/array) - Taxonomy term(s).
    • include_children (boolean) - Whether or not to include children for hierarchical taxonomies. Defaults to true.
    • operator (string) - Operator to test. Possible values are 'IN', 'NOT IN', 'AND'.

Important Note: tax_query takes an array of tax query arguments arrays (it takes an array of arrays) - you can see this in the second example below. This construct allows you to query multiple taxonomies by using the relation parameter in the first (outer) array to describe the boolean relationship between the taxonomy queries.

As of 3.5, a bug was fixed where tax_query would inadvertently return all posts when a result was empty.

Simple Taxonomy Query:

Display posts tagged with bob, under people custom taxonomy:

$args = array(
	'post_type' => 'post',
	'people' => 'bob'
);
$query = new WP_Query( $args );

Display posts tagged with bob, under people custom taxonomy, using tax_query:

$args = array(
	'post_type' => 'post',
	'tax_query' => array(
		array(
			'taxonomy' => 'people',
			'field' => 'slug',
			'terms' => 'bob'
		)
	)
);
$query = new WP_Query( $args );

Multiple Taxonomy Handling:

Display posts from several custom taxonomies:

$args = array(
	'post_type' => 'post',
	'people' => 'bob',
	'language' => 'english'
);
$query = new WP_Query( $args );

Display posts from several custom taxonomies, using tax_query:

$args = array(
	'post_type' => 'post',
	'tax_query' => array(
		'relation' => 'AND',
		array(
			'taxonomy' => 'movie_genre',
			'field' => 'slug',
			'terms' => array( 'action', 'comedy' )
		),
		array(
			'taxonomy' => 'actor',
			'field' => 'id',
			'terms' => array( 103, 115, 206 ),
			'operator' => 'NOT IN'
		)
	)
);
$query = new WP_Query( $args );

Display posts that are in the quotes category OR have the quote format:

$args = array(
	'post_type' => 'post',
	'tax_query' => array(
		'relation' => 'OR',
		array(
			'taxonomy' => 'category',
			'field' => 'slug',
			'terms' => array( 'quotes' )
		),
		array(
			'taxonomy' => 'post_format',
			'field' => 'slug',
			'terms' => array( 'post-format-quote' )
		)
	)
);
$query = new WP_Query( $args );

搜索

Show posts based on a keyword search.

  • s (string) - Search keyword.

Show Posts based on a keyword search

Display posts that match the search term "keyword":

$query = new WP_Query( 's=keyword' );

文章 & 页面

Display content based on post and page parameters.

  • p (int) - use post id.
  • name (string) - use post slug.
  • page_id (int) - use page id.
  • pagename (string) - use page slug.
  • post_parent (int) - use page id. Return just the child Pages.
  • post__in (array) - use post ids. Specify posts to retrieve.
  • post__not_in (array) - use post ids. Specify post NOT to retrieve.

Show Post/Page by ID

Display post by ID:

$query = new WP_Query( 'p=7' );

Display page by ID:

$query = new WP_Query( 'page_id=7' );

Show Post/Page by Slug

Display post by slug:

$query = new WP_Query( 'name=about-my-life' );

Display page by slug:

$query = new WP_Query( 'pagename=contact' );

Show Child Posts/Pages

Display child page using the slug of the parent and the child page, separated by a slash (e.g. 'parent_slug/child_slug'):

$query = new WP_Query( 'pagename=contact_us/canada' );

Display child pages using parent page ID:

$query = new WP_Query( 'post_parent=93' );

Display only top-level pages, exclude all child pages:

$query = new WP_Query( 'post_parent=0' );

Multiple Posts/Pages Handling

Display only the specific posts:

$query = new WP_Query( array( 'post_type' => 'page', 'post__in' => array( 2, 5, 12, 14, 20 ) ) );

Display all posts but NOT the specified ones:

$query = new WP_Query( array( 'post_type' => 'post', 'post__not_in' => array( 2, 5, 12, 14, 20 ) ) );

Note: you cannot combine 'post__in' and 'post__not_in' in the same query.

文章类型

显示某种 文章类型 的文章.

  • post_type (string / array) - 使用文章类型. 通过 Post Types 显示文章, 默认值为 '文章';
    • 'post' - 文章.
    • 'page' - 页面.
    • 'revision' - 文章版本.
    • 'attachment' - 附件. 默认的 WP_Query 设置 'post_status'=>'publish', 但是附件默认设置为 'post_status'=>'inherit' 所有如果需要显示附件,你需要设置文章状态为 'inherit' 或 'any'.
    • 'any' - 显示所有文章类型,除了‘revisions’和'exclude_from_search'设置为 TRUE的.
    • 自定义文章类型 (e.g. movies)

通过文章类型显示文章

只显示页面:

$query = new WP_Query( 'post_type=page' );

显示 'any' 文章类型 (显示所有文章类型,除了‘revisions’和'exclude_from_search'设置为 TRUE的):

$query = new WP_Query( 'post_type=any' );

显示处于多个文章类型中某一个的文章,包括自定义文章类型:

$query = new WP_Query( array( 'post_type' => array( 'post', 'page', 'movie', 'book' ) ) );

文章状态

显示处于某种文章状态 文章状态的文章.

  • post_status (string / array) - use post status. Retrieves posts by Post Status. Default value is 'publish', but if the user is logged in, 'private' is added. And if the query is run in an admin context (administration area or AJAX call), protected statuses are added too. By default protected statuses are 'future', 'draft' and 'pending'.
    • 'publish' - a published post or page.
    • 'pending' - post is pending review.
    • 'draft' - a post in draft status.
    • 'auto-draft' - a newly created post, with no content.
    • 'future' - a post to publish in the future.
    • 'private' - not visible to users who are not logged in.
    • 'inherit' - a revision. see get_children.
    • 'trash' - post is in trashbin (available with Version 2.9).
    • 'any' - retrieves any status except those from post types with 'exclude_from_search' set to true.

显示某种文章状态的文章

只显示草稿:

$query = new WP_Query( 'post_status=draft' );

显示处于多个文章状态中其中一个状态的文章:

$query = new WP_Query( array( 'post_status' => array( 'pending', 'draft', 'future' ) ) );

显示所有附件:

$query = new WP_Query( array( 'post_status' => 'any', 'post_type' => 'attachment' ) );

分页

  • nopaging (boolean) - show all posts or use pagination. Default value is 'false', use paging.
  • posts_per_page (int) - number of post to show per page (available with Version 2.1, replaced showposts parameter). Use 'posts_per_page'=>-1 to show all posts. Note: if the query is in a feed, wordpress overwrites this parameter with the stored 'posts_per_rss' option. To reimpose the limit, try using the 'post_limits' filter, or filter 'pre_option_posts_per_rss' and return -1
  • posts_per_archive_page (int) - number of posts to show per page - on archive pages only. Over-rides posts_per_page and showposts on pages where is_archive() or is_search() would be true.
  • offset (int) - number of post to displace or pass over. Note: Setting offset parameter will ignore the paged parameter.
  • paged (int) - number of page. Show the posts that would normally show up just on page X when using the "Older Entries" link.

每页显示几篇文章

每页显示3篇文章:

$query = new WP_Query( 'posts_per_page=3' );

显示所有文章

在一页中显示所有文章:

$query = new WP_Query( 'posts_per_page=-1' );

通过禁用分页显示所有文章:

$query = new WP_Query( 'nopaging=true' );

跳过几篇文章

从第4篇文章开始显示:

$query = new WP_Query( 'offset=3' ) );

显示前3篇文章后面的文章,每页显示5篇

$query = new WP_Query( array( 'posts_per_page' => 5, 'offset' => 3 ) );

显示第几页的文章

显示第6页的文章:

$query = new WP_Query( 'paged=6' );

显示当前页面的文章

显示当前页面的文章:

$query = new WP_Query( array( 'paged' => get_query_var( 'paged' ) ) );

Display posts from the current page and set the 'paged' parameter to 1 when the query variable is not set (first page). 显示当前页面的文章,当前页面的查询参数没有设置时,设置'paged'为1(第一页)

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$query = new WP_Query( array( 'paged' => $paged ) );

分页注意事项: Use get_query_var('page'); if you want your query to work in a Page template that you've set as your static front page. The query variable 'page' also holds the pagenumber for a single paginated Post or Page that includes the <!--nextpage--> Quicktag in the post content.

Display posts from current page on a static front page:

$paged = (get_query_var('page')) ? get_query_var('page') : 1;
$query = new WP_Query( array( 'paged' => $paged ) );

排序

Sort retrieved posts.

  • order (string) - Designates the ascending or descending order of the 'orderby' parameter. Defaults to 'DESC'.
    • 'ASC' - ascending order from lowest to highest values (1, 2, 3; a, b, c).
    • 'DESC' - descending order from highest to lowest values (3, 2, 1; c, b, a).
  • orderby (string) - Sort retrieved posts by parameter. Defaults to 'date'.
    • 'none' - No order (available with Version 2.8).
    • 'ID' - Order by post id. Note the captialization.
    • 'author' - Order by author.
    • 'title' - Order by title.
    • 'name' - Order by post name (post slug).
    • 'date' - Order by date.
    • 'modified' - Order by last modified date.
    • 'parent' - Order by post/page parent id.
    • 'rand' - Random order.
    • 'comment_count' - Order by number of comments (available with Version 2.9).
    • 'menu_order' - Order by Page Order. Used most often for Pages (Order field in the Edit Page Attributes box) and for Attachments (the integer fields in the Insert / Upload Media Gallery dialog), but could be used for any post type with distinct 'menu_order' values (they all default to 0).
    • 'meta_value' - Note that a 'meta_key=keyname' must also be present in the query. Note also that the sorting will be alphabetical which is fine for strings (i.e. words), but can be unexpected for numbers (e.g. 1, 3, 34, 4, 56, 6, etc, rather than 1, 3, 4, 6, 34, 56 as you might naturally expect). Use 'meta_value_num' instead for numeric values.
    • 'meta_value_num' - Order by numeric meta value (available with Version 2.8). Also note that a 'meta_key=keyname' must also be present in the query. This value allows for numerical sorting as noted above in 'meta_value'.
    • 'post__in' - Preserve post ID order given in the post__in array (available with Version 3.5).

Show Posts sorted by Title, Descending order

Display posts sorted by post title in a descending order:

$query = new WP_Query( array ( 'orderby' => 'title', 'order' => 'DESC' ) );

Show Random Post

Display one random post:

$query = new WP_Query( array ( 'orderby' => 'rand', 'posts_per_page' => '1' ) );

Show Popular Posts

Display posts ordered by comment count:

$query = new WP_Query( array( 'orderby' => 'comment_count' ) );

Show Products sorted by Price

Display posts with 'Product' type ordered by 'Price' custom field:

$query = new WP_Query( array ( 'post_type' => 'product', 'orderby' => 'meta_value', 'meta_key' => 'price' ) );

Multiple 'orderby' values

Display pages ordered by 'title' and 'menu_order'. (title is dominant):

$query = new WP_Query( array( 'post_type' => 'page', 'orderby' => 'title menu_order', 'order' => 'ASC' ) );

'orderby' with 'meta_value' and custom post type

Display posts of type 'my_custom_post_type', ordered by 'age', and filtered to show only ages 3 and 4 (using meta_query).

 $args = array(
   'post_type' => 'my_custom_post_type',
   'meta_key' => 'age',
   'orderby' => 'meta_value_num',
   'order' => 'ASC',
   'meta_query' => array(
       array(
           'key' => 'age',
           'value' => array(3, 4),
           'compare' => 'IN',
       )
   )
 );
 $query = new WP_Query($args);

置顶文章

Show Sticky Posts or ignore them.

  • ignore_sticky_posts (boolean) - ignore sticky posts or not (available with Version 3.1, replaced caller_get_posts parameter). Default value is 0 - don't ignore sticky posts. Note: ignore/exclude sticky posts being 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.

Show Sticky Posts

Display just the first sticky post:

$sticky = get_option( 'sticky_posts' );
$query = new WP_Query( 'p=' . $sticky[0] );

Display just the first sticky post, if none return the last post published:

$args = array(
	'posts_per_page' => 1,
	'post__in'  => get_option( 'sticky_posts' ),
	'ignore_sticky_posts' => 1
);
$query = new WP_Query( $args );

Display just the first sticky post, if none return nothing:

$sticky = get_option( 'sticky_posts' );
$args = array(
	'posts_per_page' => 1,
	'post__in'  => $sticky,
	'ignore_sticky_posts' => 1
);
$query = new WP_Query( $args );
if ( $sticky[0] ) {
	// insert here your stuff...
}

Don't Show Sticky Posts

Exclude all sticky posts from the query:

$query = new WP_Query( array( 'post__not_in' => get_option( 'sticky_posts' ) ) );

Exclude sticky posts from a category. Return ALL posts within 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 = new WP_Query( array( 'ignore_sticky_posts' => 1, 'posts_per_page' => 3, 'cat' => 6 );

Exclude sticky posts from a category. Return posts within the category, but exclude sticky posts completely, and adhere to paging rules:

$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$sticky = get_option( 'sticky_posts' );
$args = array(
	'cat' => 3,
	'ignore_sticky_posts' => 1,
	'post__not_in' => $sticky,
	'paged' => $paged
);
$query = new WP_Query( $args );

时间

Show posts associated with a certain time period.

  • year (int) - 4 digit year (e.g. 2011).
  • monthnum (int) - Month number (from 1 to 12).
  • w (int) - Week of the year (from 0 to 53). Uses the MySQL WEEK command. The mode is dependent on the "start_of_week" option.
  • day (int) - Day of the month (from 1 to 31).
  • hour (int) - Hour (from 0 to 23).
  • minute (int) - Minute (from 0 to 60).
  • second (int) - Second (0 to 60).

Returns posts for just the current date:

$today = getdate();
$query = new WP_Query( 'year=' . $today["year"] . '&monthnum=' . $today["mon"] . '&day=' . $today["mday"] );

Returns posts for just the current week:

$week = date('W');
$year = date('Y');
$query = new WP_Query( 'year=' . $year . '&w=' . $week );

Returns posts dated December 20:

$query = new WP_Query( '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 March 1 to March 15, 2010:

// 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, 2010
	$where .= " AND post_date >= '2010-03-01' AND post_date < '2010-03-16'";
	return $where;
}

add_filter( 'posts_where', 'filter_where' );
$query = new WP_Query( $query_string );
remove_filter( 'posts_where', 'filter_where' );

Return posts from the last 30 days:

// 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;
}

add_filter( 'posts_where', 'filter_where' );
$query = new WP_Query( $query_string );
remove_filter( 'posts_where', 'filter_where' );

Return posts 30 to 60 days old

// 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;
}

add_filter( 'posts_where', 'filter_where' );
$query = new WP_Query( $query_string );
remove_filter( 'posts_where', 'filter_where' );

自定义字段

Show posts associated with a certain custom field.

  • meta_key (string) - Custom field key.
  • meta_value (string) - Custom field value.
  • meta_value_num (number) - Custom field value.
  • meta_compare (string) - Operator to test the 'meta_value'. Possible values are '!=', '>', '>=', '<', or '<='. Default value is '='.
  • meta_query (array) - Custom field parameters (available with Version 3.1).
    • key (string) - Custom field key.
    • value (string|array) - Custom field value (Note: Array support is limited to a compare value of 'IN', 'NOT IN', 'BETWEEN', or 'NOT BETWEEN') (This value may be omitted when using the 'EXISTS' or 'NOT EXISTS' comparisons in WordPress 3.5 and up)
    • compare (string) - Operator to test. Possible values are '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS' (only in WP >= 3.5), and 'NOT EXISTS' (also only in WP >= 3.5). Default value is '='.
    • type (string) - Custom field type. Possible values are 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'. Default value is 'CHAR'.

The 'type' DATE works with the 'compare' value BETWEEN only if the date is stored at the format YYYYMMDD and tested with this format.

Simple Custom Field Query:

Display posts where the custom field key is 'color', regardless of the custom field value:

$query = new WP_Query( 'meta_key=color' );

Display posts where the custom field value is 'blue', regardless of the custom field key:

$query = new WP_Query( 'meta_value=blue' );

Display Page where the custom field value is 'blue', regardless of the custom field key:

$query = new WP_Query( 'meta_value=blue&post_type=page' );

Display posts where the custom field key is 'color' and the custom field value is 'blue':

$query = new WP_Query( array( 'meta_key' => 'color', 'meta_value' => 'blue' ) );

Display posts where the custom field key is 'color' and the custom field value IS NOT 'blue':

$query = new WP_Query( array( 'meta_key' => 'color', 'meta_value' => 'blue', 'meta_compare' => '!=' ) );

Display 'product'(s) where the custom field key is 'price' and the custom field value that is LESS THAN OR EQUAL TO 22.
By using the 'meta_value' parameter the value 99 will be considered greater than 100 as the data are stored as 'strings', not 'numbers'. For number comparison use 'meta_value_num'.

$query = new WP_Query( array( 'meta_key' => 'price', 'meta_value' => '22', 'meta_compare' => '<=', 'post_type' => 'product' ) );

Display posts with a custom field value of zero (0), regardless of the custom field key:

$query = new WP_Query( array ( 'meta_value' => '_wp_zero_value' ) );

Single Custom Field Handling:

Display posts from a single custom field:

$args = array(
	'post_type' => 'product',
	'meta_query' => array(
		array(
			'key' => 'color',
			'value' => 'blue',
			'compare' => 'NOT LIKE'
		)
	)
);
$query = new WP_Query( $args );

(Note that meta_query expects nested arrays, even if you only have one query.)

Multiple Custom Field Handling:

Display posts from several custom field:

$args = array(
	'post_type' => 'product',
	'meta_query' => array(
		array(
			'key' => 'color',
			'value' => 'blue',
			'compare' => 'NOT LIKE'
		),
		array(
			'key' => 'price',
			'value' => array( 20, 100 ),
			'type' => 'numeric',
			'compare' => 'BETWEEN'
		)
	)
);
$query = new WP_Query( $args );

Display posts that have meta key 'color' NOT LIKE value 'blue' OR meta key 'price' with values BETWEEN 20 and 100:

$args = array(
	'post_type' => 'product',
	'meta_query' => array(
		'relation' => 'OR',
		array(
			'key' => 'color',
			'value' => 'blue',
			'compare' => 'NOT LIKE'
		),
		array(
			'key' => 'price',
			'value' => array( 20, 100 ),
			'type' => 'numeric',
			'compare' => 'BETWEEN'
		)
	)
);
$query = new WP_Query( $args );

权限

  • perm (string) - User permission.

Show posts if user has the appropriate capability:

Display published and private posts, if the user has the appropriate capability:

$query = new WP_Query( array( 'post_status' => array( 'publish', 'private' ), 'perm' => 'readable' ) );

缓存

Stop the data retrieved from being added to the cache.

  • cache_results (boolean) - Post information cache.
  • update_post_meta_cache (boolean) - Post meta information cache.
  • update_post_term_cache (boolean) - Post term information cache.

Show Posts witout adding post information to the cache

Display 50 posts, but don't add post information to the cache:

$query = new WP_Query( array( 'posts_per_page' => 50, 'cache_results' => false ) );

Show Posts witout adding post meta information to the cache

Display 50 posts, but don't add post meta information to the cache:

$query = new WP_Query( array( 'posts_per_page' => 50, 'update_post_meta_cache' => false ) );

Show Posts witout adding post term information to the cache

Display 50 posts, but don't add post term information to the cache:

$query = new WP_Query( array( 'posts_per_page' => 50, 'update_post_term_cache' => false ) );

In general usage you should not need to use these, adding to the cache is the right thing to do, however they may be useful in specific circumstances. An example of such circumstances might be when using a WP_Query to retrieve a list of post titles and URLs to be displayed, but in which no other information about the post will be used and the taxonomy and meta data won't be needed. By not loading this information, you can save time from the extra unnecessary SQL queries.

Note: If a persistent object cache backend (such as memcached) is used, these flags are set to false by default since there is no need to update the cache every page load when a persistent cache exists.

返回字段

Set return values.

  • fields (string|array) - Which fields to return. Defaults to all.
    • 'ids' - Return an array of post IDs.
    • 'id=>parent' - Return an associative array [ parent => ID, … ].
    • any other value or empty (default): return an array of post objects

过滤器

  • posts_distinct - Alters SQL 'DISTINCTROW' clause to the query that returns the post array.
  • posts_groupby - Alters SQL 'GROUP BY' clause of the query that returns the post array.
  • posts_join - Alters SQL 'JOIN' clause of the query that returns the post array.
  • post_limits - Alters SQL 'LIMIT' clause of the query that returns the post array.
  • posts_orderby - Alters SQL 'ORDER BY' clause of the query that returns the post array.
  • posts_where - Alters SQL 'WHERE' clause of the query that returns the post array.
  • posts_join_paged - Alters SQL paging for posts using 'JOIN' clause of the query that returns the post array.
  • posts_where_paged - Alters SQL paging for posts using 'WHERE' clause of the query that returns the post array.
  • posts_clauses - Alters all the SQL clauses above in one go. It gives you an array of elements that are easy to alter (available with Version 3.1).

Note, that there are more filters than the mentioned. As it is hard to keep the codex up to date, please inspect the get_posts(); function inside the WP_Query class yourself (/wp-includes/query.php).

源文件

WP_Query() is located in wp-includes/query.php.

资源

相关信息

Articles

Code Documentation

See also index of Class Reference and index of Function Reference.