之前大叔介紹過 WordPress 相關文章實現的方法,例:《代碼實現 WordPress 相關文章》,那麼今天説的這個教程,是從優化角度來更合理的實現 WordPress 相關文章的,至於客觀喜歡哪個,自己決定吧!
策略:文章內容相關程度: 手動指定 > 標籤 > 分類 > 隨機

實現方式:下面代碼直接加到 functions.php 中即可
- function add_related_posts($content){
- return $content . wp_related_posts();
- }
- function wp_related_posts(){
- global $post;
- $num = 5;
- $counter = 1;
- $exclude_id = get_post_meta($post->ID,'related',true);
- if ($exclude_id){
- $args = array(
- 'post_type' => array('post'),
- 'posts_per_page' => $num
- $posts = get_posts($args);
- foreach($posts as $sb){
- $output .= '<li><a href="' . get_permalink($sb->ID) . '">' . $sb->post_title . '</a></li>';
- $i++;
- }
- if( $i < $num){
- $tagsid = array();
- $catid = array();
- $thisid[] = $post->ID;
- $posttags = get_the_tags();
- $catids = get_the_category();
- if(!emptyempty($posttags)) {
- foreach($posttags as $tag) {
- $tagsid[] = $tag->term_id;
- }
- if(!emptyempty($catids)) {
- foreach($catids as $cat) {
- $catid[] = $cat->term_id;
- }
- $args = array(
- 'post__not_in' => $thisid,
- 'posts_per_page' => ($num - $i),
- 'relation' => 'OR',
- array(
- 'taxonomy' => 'post_tag',
- 'terms' => $tagsid,
- array(
- 'field' => 'term_id',
- ),
- );
- $rsp = get_posts($args );
- foreach($rsp as $sb){
- $output .= '<li><a href="' . get_permalink($sb->ID) . '">' . $sb->post_title . '</a></li>';
- $i++;
- }
- $final = '<h3> 相關文章</h3><ul>' . $output . '</ul>';
- return $final;
-

如想自定位置,並調整樣式,則去掉
the_content的鈎子,然後手動調用wp_related_posts函數騷年,創作吧。。。。
explode(',', $exclude_id),
array(
$catid,