WordPress 不用插件实现相关文章效果

WordPress教程 4116

之前博客吧介绍了使用博客插件实现WordPress相关文章效果《WordPress 相关文章插件WordPress Related Posts》,但众所周知的是使用太多的博客插件会使WordPress博客的速度变慢,影响用户体验,所以博客插件是能少用一个就少用一个,本篇中博客吧将介绍不用插件实现相关文章的功能效果。

方法步骤:

  1. 登陆自己的WordPress博客进入后台,点击外观选项卡下的“编辑”进入主题编辑界面
  2. 选择博客主题文件single.php,在需要设置相关文章效果的相应位置添加以下代码,然后提交保存即可:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    <h3>相关日志</h3>
    <ul>
    <?php
    $tags = wp_get_post_tags($post->ID);
    if ($tags) {
    $first_tag = $tags[0]->term_id;
    $args=array(
    'tag__in' => array($first_tag),
    'post__not_in' => array($post->ID),
    'showposts'=>10,
    'caller_get_posts'=>1
    );
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
    <li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title();?> <?php comments_number(' ','(1)','(%)'); ?></a></li>
    <?php
    endwhile;
    }
    }
    wp_reset_query();
    ?>
    </ul>

效果演示:

提醒:如果主题作者没有对相关文章制作样式,那就需要自己动手了。

精品推荐: