新浪微博的置顶功能相信大家非常熟悉,其实 WordPress 早在 2.7 之后就拥有了文章置顶的功能。但是,实际上这个功能在大多主题上却没太多用武之地。我想其中的一个原因,是很多像我们这样的个人博客,首页基本上只展示最新的5-10篇文章,如果再置顶个几篇,首页的内容基本上就不变了。

不过,如果我们换个角度,把置顶文章从页面中央移到侧栏,这样的 效果应该会不错,首先首页的文章列表中不会受到置顶的干扰,同时位于侧栏的置顶文章又有类似文章推荐的效果,我们动手来试试。

整个解决方案需要考虑到两点:

  1. 首页展示文章的时候要忽略置顶文章,这里的忽略是指不置顶显示;
  2. 侧栏需要增加显示置顶文章列表的小工具;

步骤一:首页忽略置顶文章

在主题的 functions.php 中加入以下代码:

/*
 * Alter the main loop
 */
function dangopress_alter_main_loop($query)
{
    /* Only for main loop in home page */
    if (!$query->is_home() || !$query->is_main_query())
        return;

    // ignore sticky posts, don't show them in the start
    $query->set('ignore_sticky_posts', 1);
}
add_action('pre_get_posts', 'dangopress_alter_main_loop'); 

这里通过指定ignore_sticky_posts为1,查询出的文章列表就会忽略置顶文章。

慎用 query_posts,虽然它用起来简单,但是会造成重复查询数据库,性能比较差。

步骤二: 获取置顶文章列表

将以下代码添加到主题的 functions.php 文件中:

/*
 * Get a list of sticky posts
 */
function dangopress_get_sticky_posts($post_num = 10, $chars = 30)
{
    $args = array(
        'numberposts' => $posts_num,
        'post__in' => get_option('sticky_posts'),
        'orderby' => 'modified'
    );

    $sticky_posts = get_posts($args);
    $output = '';

    foreach ($sticky_posts as $post) {
        $permalink = get_permalink($post->ID);
        $title = $post->post_title;
        $title_attr = esc_attr(strip_tags($title));

        $link = '<a href="' . $permalink. '" rel="bookmark" title="推荐阅读《' . $title_attr . '》">';
        $link .= wp_trim_words($title, $chars) . '</a>';

        $output .= '<li>' . $link . '</li>';
    }

    echo $output;
}

上面的代码通过get_option('sticky_posts')来获取置顶文章 ID 列表,配合 get_posts 方法来获取置顶文章列表。该函数支持两个参数,分别是文章列表个数和文章标题显示长度(超过会截断)。

步骤三: 增加小工具

我们使用最简单的方法添加一个置顶文章列表的小工具,将以下代码放到主题的 sidebar.php 文件中:

<div class="widget widget-sticky-posts">
<h3>置顶文章</h3>
<ul><?php dangopress_get_sticky_posts(8, 30); ?></ul>
</div>

不过这里还是推荐通过Tab 选项卡的形式展示,最终的效果可以看我的博客侧栏。

转载请注明转自: 团子的小窝 , 本文固定链接: WordPress 置顶文章推荐

  1. 所谓刚子's avatar
    所谓刚子 发表于 2013-10-09 6:07:41 回复 #1

    不错不错 来学习了

  2. 所谓刚子's avatar
    所谓刚子 发表于 2013-10-09 6:02:09 回复 #2

    主题不错 哈哈哈