标签: 插件

  • 强大的无插件实现相关文章,永不落空版

    相关文章使很多wordpress的Bloger关注的问题,相关文章可以大大增加PV,也可以使你八百年前发布的文字能出个头。很多Bloger都是用插件实现的,但对于我们这些有“代码洁癖”和效率强迫症的人来说插件不是最佳的实现方式。so找到下面代码实现相关文章。

    原理是先查看与标签(关键字)相关的标题,如果没有那就取同分类下的X篇文字(不要告诉我分类下没有5篇文字 -_- ! )。

    源代码来自:http://kan.willin.org/ 我做了修正:修正了当取得同分类下文章的时候还会显示没有相关的小BUG。


    <h3>你可能也感兴趣:</h3>
    <ul>
    <?php
    $post_num = 5; // 數量設定.
    global $post;
    $tmp_post = $post;
    $tags = ''; $i = 0; // 先取 tags 文章.
    $exclude_id = $post->ID;
    $posttags = get_the_tags();
    if ( $posttags ) {
      foreach ( $posttags as $tag ) $tags .= $tag->name . ',';
      $tags = strtr(rtrim($tags, ','), ' ', '-');
      $myposts = get_posts('numberposts='.$post_num.'&tag='.$tags.'&exclude='.$exclude_id);
      foreach($myposts as $post) {
        setup_postdata($post);
        ?>
        <li> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php
        $exclude_id .= ','.$post->ID; $i ++;
      }
    }
    if ( $i < $post_num ) { // 當 tags 文章數量不足, 再取 category 補足.
      $post = $tmp_post; setup_postdata($post);
      $cats = ''; $post_num -= $i;
      foreach ( get_the_category() as $cat ) $cats .= $cat->cat_ID . ',';
      $cats = strtr(rtrim($cats, ','), ' ', '-');
      $myposts = get_posts('numberposts='.$post_num.'&category='.$cats.'&exclude='.$exclude_id);
      foreach($myposts as $post) {
        setup_postdata($post);
        ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php
        $i ++;
      }
    }
    if ( $i == 0 ) echo '<li>尚無相關文章</li>';
    $post = $tmp_post; setup_postdata($post);
    ?>
    </ul>