WordPress 有很多實現相關文章功能的外掛,外掛的優點是配置簡單,但是可能會對網站的速度造成一些小的影響,所以很多人還是比較喜歡用程式碼實現需要的功能,但是話又說回來了,程式碼實現也有缺點,就是配置複雜,不懂程式碼的人完全摸不著頭腦或者只能照搬別人的程式碼,還不如用外掛。
這裡我整理編寫了幾種用程式碼實現相關文章的方法,這其中會詳細標明各部分程式碼的作用,以及如何自定義你想要的功能,希望對大家有所幫助,有什麼問題可以給本文發表評論,我會及時給你回覆。開始之前,說明一點,以下所有方法輸出的 HTML 程式碼格式都是以下形式,你可以根據需要進行修改:
| <ul id="xxx"> <li>* <a title=" 文章標題 1" rel="bookmark" href=" 文章連結 1"> 文章標題 1</a></li> <li>* <a title=" 文章標題 2" rel="bookmark" href=" 文章連結 2"> 文章標題 2</a></li> ...... </ul> |
方法一:標籤相關
首先獲取文章的所有標籤,接著獲取這些標籤下的 n 篇文章,那麼這 n 篇文章就是與該文章相關的文章了。現在可以見到的 WordPress 相關文章外掛都是使用的這個方法。下面是實現的程式碼:
| <ul id="tags_related"> <?php $post_tags = wp_get_post_tags($post->ID); if ($post_tags) { foreach ($post_tags as $tag) { // 獲取標籤列表 $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(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li> <?php endwhile; else : ?> <li>* 暫無相關文章</li> <?php endif; wp_reset_query(); } ?> </ul> |
使用說明:” 不包括的分類 ID” 指的是相關文章不顯示該分類下的文章,將同行的 NULL 改成文章分類的 ID 即可,多個 ID 就用半形逗號隔開。因為這裡限制只顯示 6 篇相關文章,所以不管給 query_posts() 的引數 tag__in 賦多少個值,都是隻顯示一個標籤下的 6 篇文章,除非第一個標籤有 1 篇,第二個標籤有 2 篇,第三個有 3 篇。。。。。。所以如果這篇文章有多個標籤,那麼我們採取的做法是隨機獲取一個標籤的 id,賦值給 tag__in 這個引數,獲取該標籤下的 6 篇文章。
方法二:分類相關
本方法是透過獲取該文章的分類 id,然後獲取該分類下的文章,來達到獲取相關文章的目的。
| <ul id="cat_related"> <?php $cats = wp_get_post_categories($post->ID); if ($cats) { $cat = get_category( $cats[0] ); $first_cat = $cat->cat_ID; $args = array( 'category__in' => array($first_cat), '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(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li> <?php endwhile; else : ?> <li>* 暫無相關文章</li> <?php endif; wp_reset_query(); } ?> </ul> |