給單篇文章的下面再加上幾篇相關文章,這樣如果訪客閱讀了某篇文章,還可以推薦同分類下,或者同標籤的一些文章。實現這個功能最常見的外掛就是 「無覓」 外掛了。
下面先提供一個獲取同屬一個分類或標籤的相關文章實現方法:
- <ul class="tags_related">
- <?php
- $post_tags = wp_get_post_tags($post->ID); //獲取該文章的標籤
- if ($post_tags) {
- foreach ($post_tags as $tag){
- // 獲取標籤 id 陣列
- $tag_list[] .= $tag->term_id;
- }
- // 隨機獲取標籤列表中的一個標籤
- $post_tag = $tag_list[ mt_rand(0, count($tag_list) - 1) ];
- //準備好 query_posts() 的引數
- $args = array(
- 'tag__in' => array($post_tag),
- 'category__not_in' => array(NULL), // 不包括的分類 ID
- 'post__not_in' => array($post->ID),
- 'showposts' => 6, // 顯示相關文章數量
- 'caller_get_posts' => 1
- );
- //獲取文章
- query_posts($args);
- if (have_posts()) : while (have_posts()) : the_post(); update_post_caches($posts); ?>
- <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
- <?php endwhile;
- else : ?>
- <li> 無相關文章</li>
- <?php endif; }else{ ?>
- <?php $ashu_cats = wp_get_post_categories($post->ID); //獲取該文章所屬分類
- if( $ashu_cats ){
- $args = array(
- 'category__in' => array( $ashu_cats[0] ),
- 'post__not_in' => array( $post->ID ),
- 'showposts' => 6,
- 'caller_get_posts' => 1
- );
- //查詢同屬一個分類的文章
- query_posts($args);
- if( have_posts()):while(have_posts()):the_post();update_post_caches($posts);?>
- <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
- <?php endwhile; endif; wp_reset_query();
- } } ?>
- </ul>
這樣實現的相關文章只是一個文章標題列表,可根據自己的設計,修改成帶縮圖外觀像 「無覓」 的相關文章。。。