当前位置: 首页 » 笔记 » wordpress WP_Query函数 ignore_sticky_posts忽略置顶文章

wordpress WP_Query函数 ignore_sticky_posts忽略置顶文章

零分笔记1,5052024-02-16 14:07

在首页某个区块显示置顶文章,通过WP_Query,一直没有达到想要的效果,刚开始以为posts_per_page失效!

$where = array('posts_per_page' =>3,'post__in'  => get_option( 'sticky_posts' ));
$the_query = new WP_Query($where);

无论如何设置,都会显示全部的置顶文章。

修改query_posts查询,还是一样的问题,无法达到预期想要的显示文章篇数​。

修改​显示文章的方式:showposts,但这个好像已经被新版的wordpress弃用了,依然无法达到预期的效果​。

通过打印WP_Query发现,query上的查询语句limit确实是posts_per_page设置的数量,但输出的文章数量却总是和这个数字不对​。

试了下删除post__in,取消大多数文章置顶,仅仅保留几篇,方便前端查看输出文章

发现还是会显示输出的置顶文章。

开始以为缓存的问题,清除浏览器,更换浏览器,​结果还是一样。

翻阅了很多资料,才发现这个参数​:​ignore_sticky_posts

ignore_sticky_posts (boolean) – ignore post stickiness (available since version 3.1, replaced caller_get_posts parameter). false (default): move sticky posts to the start of the set. true: do not move sticky posts to the start of the set.

ignore_sticky_posts(布尔值)–忽略post粘性(自3.1版本起提供,已替换caller_get_posts参数)。false(默认值):将粘性帖子移动到集合的开头。true:不要将粘性帖子移到集合的开头。

终于在官网文档找到了单独调用置顶文章的方法​:

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

添加了下ignore_sticky_posts参数(默认是false),可以成功的调用指定数量的置顶文章

$where = array('posts_per_page' =>3,'ignore_sticky_posts' => 1,'post__in'  => get_option( 'sticky_posts' ));
$the_query = new WP_Query($where);

至此,成功的在首页区块​调用指定数量的置顶文章!

END
零分站龄17年资深站长
一个喜欢折腾,却又折腾不出像样东西的,不会PHP的PHP程序员!
2517
文章
13
分类
3818
标签
3
友链
onlinelovesky317355746vipsever@vip.qq.com