智狐工作室出品
www.seozn.com

WordPress常用函数WP_Query

WordPress常用函数 WP_Query 是在制作WordPress CMS主题时必用函数,简单而且好用。WP_Query 是WordPress的精华,下面我们将实例说明 WP_Query 的用法。

按 Author 来调用文章

指定作者ID来调用文章

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

按照作者昵称来调用文章

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

按ID调用多个作者的文章

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

过滤掉某个作者的文章

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

按 Category 来调用文章

按分类ID调用某个分类的文章

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

按分类别名指定调用某个分类的文章

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

按分类ID调用多个分类文章

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

按分类别名调用多个分类文章

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

过滤掉某些分类ID

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

调用同时属于分类ID为2和6的两个分类下的文章(交集)

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

调用属于分类ID为2或者6下的文章

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

调用不属于分类ID为2或者6下的文章

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

按 Tag 调用文章

调用含有标签 cooking 的文章

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

按标签ID调用文章

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

调用标签 bread,baking 的文章

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

调用同时含有标签 bread,baking,recipe 的文章(交集)

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

调用标签ID为37和47的文章(交集)

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

调用标签ID为37或47的文章

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

过滤掉标签ID为37或47的文章

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

按 Post 和 Page 调用文章

指定文章的ID调用文章

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

指定页面的ID调用页面

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

指定文章别名调用文章

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

指定页面别名调用页面

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

别名特殊调用,指定层次关系下(parent_slug/child_slug)

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

按ID和文章属性调用多个页面

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

按ID过滤掉多个页面

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

属性调用

调用全部页面

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

调用自定义文章(WordPress 3.4 以上适用)

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

状态调用

可用的文章状态有:

  • publish‘ – 已发布
  • pending‘ – 审核中
  • draft‘ – 草稿
  • auto-draft‘ – 自动草稿
  • future‘ – 定时发布
  • private‘ – 私有
  • inherit‘ – 修订版(自动存档)
  • trash‘ – 回收站
  • any‘ – 任何

调用草稿

$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' ) );

按分页调用

一页显示10篇文章

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

所有文章在一页显示

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

显示第6页的文章

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

Display posts from current page

$query = new WP_Query( '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 = (get_query_var('paged')) ? get_query_var('paged') : 1;
$query = new WP_Query( 'paged=' . $paged );

Display posts from current page on a static front page

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

文章过滤

过滤掉前3篇文章

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

每5篇文章分页一次,并且过滤掉第一篇文章

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

文章排序

按文章名倒序排列

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

随机显示5篇文章

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

按评论数量排列

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

置顶文章

显示第一篇置顶文章

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

显示第一篇置顶文章,如果没有置顶文章则返回到最新的文章

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

显示第一篇置顶文章,如果没有置顶文章则不显示任何内容

$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...
}

不显示置顶文章

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

显示分类ID为6的分类下所有文章,并且每3篇分一页,不让置顶文章显示在最顶部

$query = new WP_Query( 'ignore_sticky_posts=1&posts_per_page=3&cat=6' );

排除置顶文章,返回到分类最新文章,按系统分页规则分页

$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 );

更多用法(英文)

Time Parameters

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' );

Custom Field Parameters

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’)
    • compare (string) – Operator to test. Possible values are ‘=’, ‘!=’, ‘>’, ‘>=’, ‘<‘, ‘<=’, ‘LIKE’, ‘NOT LIKE’, ‘IN’, ‘NOT IN’, ‘BETWEEN’, ‘NOT BETWEEN’, ‘NOT EXISTS’ (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’.

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 );

Permission Parameters

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

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

Parameters relating to caching

In addition to the parameters mentioned above, you can also pass three different cache control flags: cache_results, update_post_term_cache, and update_post_meta_cache.

If you need to stop the data retrieved from being added to the cache you can pass cache_results as false (this is a master flag that will also turn off the other two), or you can be specific and pass update_post_term_cache and/or update_post_meta_cache depending on your requirements.

// Retrieve 50 posts, but don't add post meta to the cache
$query = new WP_Query( array( 'posts_per_page' => 50, 'update_post_meta_cache' => false ) );
// Retrieve 50 posts, but don't add post information to the cache
$query = new WP_Query( array( 'posts_per_page' => 50, 'cache_results' => 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.

Post Field Parameters

  • fields
    • '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

Search Parameter

Show posts based on a keyword search

  • s (string) – Search keyword

Return posts that match the search term “keyword”:

$query = new WP_Query( 's=keyword' );
分享到:更多 ()