热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

WordPress查询函数参考:query_posts

描述Query_posts 可以用来控制在循环TheLoop中显示哪些文章。它可以接受各种参数,就像你的URL中使用的参数(例如:参数p,p4表示只显示ID为4的文章).通常的用法:在你的首页只显示一篇文章(若只想显示一个独立的页面page,可以通过WordPress管理后台,设置-

描述

Query_posts?可以用来控制在循环The Loop中显示哪些文章。它可以接受各种参数,就像你的URL中使用的参数(例如:参数p,p=4表示只显示ID为4的文章).

通常的用法:

  • 在你的首页只显示一篇文章(若只想显示一个独立的页面page,可以通过WordPress管理后台,设置 -> 阅读,在那里修改).
  • 显示一个特定的时间段内的所有文章.
  • 在首页只显示最新的文章.
  • 改变文章的显示顺序.
  • 只显示某个特定分类下的文章.
  • 不显示某个或多个分类下的文章.

重要提示

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 Note

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 (&).

 

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.

  • cat?- must use cat ids
  • category_name
  • category__and?- must use cat ids
  • category__in?- must use cat ids
  • category__not_in?- must use cat ids

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

 

Tag Parameters

Show posts associated with certain tags.

  • tag
  • tag_id?- must use tag ids
  • tag__and?- must use tag ids
  • tag__in?- must use tag ids
  • tag__not_in?- must use tag ids
  • tag_slug__and
  • tag_slug__in

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

 

作者参数

你也可以通过作者限定文章

  • author=3
  • author=-3?通过“负号”排除作者id为3的文章
  • author_name=Harriet

注释:?author_name为定义于user_nicename中的字段,author为作者的id。

排除置顶文章后依照标题排序显示所有作者ID为1的已发布页面

query_posts('caller_get_posts=1&author=1&post_type=page&post_status=publish&orderby=title&order=ASC');

 

Post & Page Parameters

Retrieve a single post or page.

  • 'p' => 27?- use the post ID to show that post
  • 'name' => 'about-my-life'?- query for a particular post that has this?Post Slug
  • 'page_id' => 7?- query for just Page ID 7
  • 'pagename' => 'about'?- note that this is not the page's title, but the page's path
  • 'posts_per_page' => 1?- use?'posts_per_page' => 3?to show 3 posts. Use?'posts_per_page' => -1?to show all posts
  • 'showposts' => 1?- use?'showposts' => 3?to show 3 posts. Use?'showposts' => -1?to show all posts.Deprecated in favor of posts_per_page
  • 'post__in' => array(5,12,2,14,7)?- inclusion, lets you specify the post IDs to retrieve
  • 'post__not_in' => array(6,2,8)?- exclusion, lets you specify the post IDs NOT to retrieve
  • 'post_type' => 'page'?- returns?Pages; defaults to value of?post; can be?any,?attachment,?page,?post, orrevision.?any?retrieves any type except revisions. Also can designate custom post types (e.g. movies).
  • 'post_status' => 'publish'?- returns publish works. Also could use?pending,?draft,?future,?private,?trash. For?inherit?see?get_children. Status of?trash?added with?Version 2.9.
  • 'post_parent' => 93?- return just the child Pages of Page 93.

To return both posts and custom post type movie

query_posts( array( 'post_type' => array('post', 'movie') ) );

 

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.

  • array('post__in'=>get_option('sticky_posts'))?- returns array of all sticky posts
  • caller_get_posts=1?- To 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.

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:

3,
   'caller_get_posts'=>1,
   'post__not_in' => $sticky,
   'paged'=>$paged,
   );
query_posts($args);
?>

 

Time Parameters

Retrieve posts belonging to a certain time period.

  • hour=?- hour (from 0 to 23)
  • minute=?- minute (from 0 to 60)
  • secOnd=?- second (0 to 60)
  • day=?- day of the month (from 1 to 31)
  • mOnthnum=?- month number (from 1 to 12)
  • year=?- 4 digit year (e.g. 2009)
  • w=?- 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 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' );

Return posts for posts for March 1 to March 15, 2009:

= '2009-03-01' AND post_date <'2009-03-16'";
    return $where;
  }
add_filter('posts_where', 'filter_where');
query_posts($query_string);
?>

Return posts from the last 30 days:

 '" . date('Y-m-d', strtotime('-30 days')) . "'";
    return $where;
  }
add_filter('posts_where', 'filter_where');
query_posts($query_string);
?>

Return posts 30 to 60 days old

= '" . 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_posts($query_string);
?>

 

Pagination Parameters

  • nopaging=true?- will disable pagination, displaying all posts
  • posts_per_page=10?- number of posts to show per page
  • paged=2?- show the posts that would normally show up just on page 2 when using the "Older Entries" link. You should set this to?get_query_var( 'paged' )?if you want your query to work with pagination.
  • order=ASC?- 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('posts_per_page=5&offset=1');

 

Orderby Parameters

Sort retrieved posts by this field.

  • orderby=author
  • orderby=date
  • orderby=title
  • orderby=modified
  • orderby=menu_order?Note:?Only works with?Pages.
  • orderby=parent
  • orderby=ID
  • orderby=rand
  • orderby=meta_value?Note:?A?meta_key=keyname?must also be present in the query.
  • orderby=none?- no order (available with?Version 2.8)
  • orderby=comment_count?- (available with?Version 2.9)

 

Order Parameters

Designates the ascending or descending order of the ORDERBY parameter.

  • order=ASC?- ascending order, lowest to highest value
  • order=DESC?- descending order, highest to lowest value

 

Custom Field Parameters

Retrieve posts (or?Pages) based on a custom field key or value.

  • meta_key=
  • meta_value=
  • meta_compare=?- operator to test the?meta_value=, 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=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');

 

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

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.

 

Examples

 

Exclude Categories From Your Home Page

Placing this code in your?index.php?file will cause your home page to display posts from all categories?exceptcategory ID 3.

You can also add some more categories to the exclude-list (tested with WP 2.1.2):

 

Retrieve a Particular Post

To retrieve a particular post, you could use the following:

If you want to use the?Read More?functionality with this query, you will need to set the global?$more?variable to 0.

 

Retrieve a Particular Page

To retrieve a particular page, you could use the following:

or

For child pages, the slug of the parent and the child is required, separated by a slash. For example:

 

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.

 

 

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 order so we get the oldest post at the top of the page.


 

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 theposts_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.

 

Example 4

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.

 

Preserving the Original Query (Pagination etc.)

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

 

 

Usage Tips

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

 

Resources

 

Related

See also index of?Function Reference?and index of?Template Tags.

推荐阅读
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • 一、Hadoop来历Hadoop的思想来源于Google在做搜索引擎的时候出现一个很大的问题就是这么多网页我如何才能以最快的速度来搜索到,由于这个问题Google发明 ... [详细]
  • 在Docker中,将主机目录挂载到容器中作为volume使用时,常常会遇到文件权限问题。这是因为容器内外的UID不同所导致的。本文介绍了解决这个问题的方法,包括使用gosu和suexec工具以及在Dockerfile中配置volume的权限。通过这些方法,可以避免在使用Docker时出现无写权限的情况。 ... [详细]
  • 推荐一个ASP的内容管理框架(ASP Nuke)的优势和适用场景
    本文推荐了一个ASP的内容管理框架ASP Nuke,并介绍了其主要功能和特点。ASP Nuke支持文章新闻管理、投票、论坛等主要内容,并可以自定义模块。最新版本为0.8,虽然目前仍处于Alpha状态,但作者表示会继续更新完善。文章还分析了使用ASP的原因,包括ASP相对较小、易于部署和较简单等优势,适用于建立门户、网站的组织和小公司等场景。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 本文介绍了如何在MySQL中将零值替换为先前的非零值的方法,包括使用内联查询和更新查询。同时还提供了选择正确值的方法。 ... [详细]
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • [译]技术公司十年经验的职场生涯回顾
    本文是一位在技术公司工作十年的职场人士对自己职业生涯的总结回顾。她的职业规划与众不同,令人深思又有趣。其中涉及到的内容有机器学习、创新创业以及引用了女性主义者在TED演讲中的部分讲义。文章表达了对职业生涯的愿望和希望,认为人类有能力不断改善自己。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文由编程笔记小编整理,介绍了PHP中的MySQL函数库及其常用函数,包括mysql_connect、mysql_error、mysql_select_db、mysql_query、mysql_affected_row、mysql_close等。希望对读者有一定的参考价值。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 推荐系统遇上深度学习(十七)详解推荐系统中的常用评测指标
    原创:石晓文小小挖掘机2018-06-18笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值, ... [详细]
  • Oracle分析函数first_value()和last_value()的用法及原理
    本文介绍了Oracle分析函数first_value()和last_value()的用法和原理,以及在查询销售记录日期和部门中的应用。通过示例和解释,详细说明了first_value()和last_value()的功能和不同之处。同时,对于last_value()的结果出现不一样的情况进行了解释,并提供了理解last_value()默认统计范围的方法。该文对于使用Oracle分析函数的开发人员和数据库管理员具有参考价值。 ... [详细]
  • 解决Cydia数据库错误:could not open file /var/lib/dpkg/status 的方法
    本文介绍了解决iOS系统中Cydia数据库错误的方法。通过使用苹果电脑上的Impactor工具和NewTerm软件,以及ifunbox工具和终端命令,可以解决该问题。具体步骤包括下载所需工具、连接手机到电脑、安装NewTerm、下载ifunbox并注册Dropbox账号、下载并解压lib.zip文件、将lib文件夹拖入Books文件夹中,并将lib文件夹拷贝到/var/目录下。以上方法适用于已经越狱且出现Cydia数据库错误的iPhone手机。 ... [详细]
author-avatar
爱情de眷恋_558
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有