給單篇文章的下面再加上幾篇相關文章,這樣如果訪客閲讀了某篇文章,還可以推薦同分類下,或者同標籤的一些文章。實現這個功能最常見的插件就是 「無覓」 插件了。

下面先提供一個獲取同屬一個分類或標籤的相關文章實現方法:

  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>  

這樣實現的相關文章只是一個文章標題列表,可根據自己的設計,修改成帶縮略圖外觀像 「無覓」 的相關文章。。。