^ 回到顶部
  • 人生没有定律,每个人都有自己的节奏
  • 本站wordpress建站教程均通过实践后发布,希望对你有帮助,如果有代码出错,请联系站长解决
  • 希望你的坚持,都是因为热爱,而不是因为不甘心
  • 8年wordpress建站经验,5星服务品质
  • 那些不愿意让你吃亏的人,才是真正值得你深交的人,也是值得你付出时间的人
  • 腾讯云3年2核2G新品轻量限时特惠只需408元

WordPress调用置顶文章及控制置顶文章显示数量的办法

在 WordPress 建站过程中,我们有时候要调用置顶的文章,并且关键的是控制显示置顶的文章的数量,你或许试了网上的很多方法,总有不如意的地方,今天一起讨论一下。

首先,你需要了解 query_posts 函数。该函数的作用就是对文章进行检索、挑选、排序,在其后的 LOOP 循环中使用经过挑选、排序的文章。例如:

2 核 2G 限时特惠 396 元/3 年    宝塔建站 10850 大礼包

<?php
query_posts('posts_per_page=10&ignore_sticky_posts=1&orderby=rand');
while(have_posts()):the_post();
 echo '<li>';the_title();echo '</li>';
endwhile;
wp_reset_query();

上面代码将随机列出一条文章的标题。

接下来,我们就是要通过对 query_posts 的参数进行调整,挑选出置顶的文章列表了。

$query_post = array(
 'posts_per_page' => 10,
 'post__in' => get_option('sticky_posts'),
 'caller_get_posts' => 1
);
query_posts($query_post);
>
<ul style="display:none;">
<?php while(have_posts()):the_post(); ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<?php
wp_reset_query();

参数用一个数组的形式放在$query_post中,关键的参数为'post__in' =>get_option('sticky_posts')和'caller_get_posts' => 0。

'post__in' => get_option('sticky_posts')确定了该 LOOP 调用的是置顶文章列表。

'caller_get_posts'的作用是排除非指定性文章,即除了置顶文章之外,不显示其他的文章。

'posts_per_page' => 10,控制文章的数量

不添加的情况下,如果置顶文章条目不足'posts_per_page'规定的值,会用最新文章替补完整。

 

赠人玫瑰,手有余香。