wordpress功能集成(十):无插件实现相关文章

给单篇文章的下面再加上几篇相关文章,这样如果访客阅读了某篇文章,还可以推荐同分类下,或者同标签的一些文章。实现这个功能最常见的插件就是 “无觅” 插件了。

下面先提供一个获取同属一个分类或标签的相关文章实现方法:

  1. <ul class="tags_related">   
  2.            
  3.         <?php   
  4.         $post_tags = wp_get_post_tags($post->ID); //获取该文章的标签   
  5.         if ($post_tags) {   
  6.             foreach ($post_tags as $tag){   
  7.                 // 获取标签id数组   
  8.                 $tag_list[] .= $tag->term_id;   
  9.             }   
  10.             // 随机获取标签列表中的一个标签   
  11.             $post_tag = $tag_list[ mt_rand(0, count($tag_list) - 1) ];   
  12.                
  13.             //准备好query_posts()的参数   
  14.             $args = array(   
  15.                 'tag__in' => array($post_tag),   
  16.                 'category__not_in' => array(NULL),      // 不包括的分类ID   
  17.                 'post__not_in' => array($post->ID),   
  18.                 'showposts' => 6,               // 显示相关文章数量   
  19.                 'caller_get_posts' => 1   
  20.             );   
  21.                
  22.             //获取文章   
  23.             query_posts($args);   
  24.                
  25.             if (have_posts()) : while (have_posts()) : the_post(); update_post_caches($posts); ?>   
  26.   
  27.                 <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>   
  28.                    
  29.             <?php endwhile;    
  30.             else : ?>   
  31.                
  32.                 <li>无相关文章</li>     
  33.                    
  34.             <?php endif; }else{ ?>   
  35.                
  36.             <?php $ashu_cats = wp_get_post_categories($post->ID); //获取该文章所属分类   
  37.             if$ashu_cats ){   
  38.                
  39.                 $args = array(   
  40.                     'category__in' => array$ashu_cats[0] ),   
  41.                     'post__not_in' => array$post->ID ),   
  42.                     'showposts' => 6,   
  43.                     'caller_get_posts' => 1   
  44.                 );   
  45.                 //查找同属一个分类的文章   
  46.                 query_posts($args);   
  47.                    
  48.                 if( have_posts()):while(have_posts()):the_post();update_post_caches($posts);?>   
  49.                    
  50.                 <li><a href="<?php the_permalink(); ?>"  title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>   
  51.                    
  52.             <?php endwhileendif; wp_reset_query();   
  53.             } } ?>   
  54.   
  55.         </ul>  

这样实现的相关文章只是一个文章标题列表,可根据自己的设计,修改成带缩略图外观像“无觅”的相关文章。。。

已有0评论

暂时木有评论.

发表评论