WordPress代码实现相关文章的几种方法

一篇十分优秀的博文

来源于:

http://www.nafanlong.com/2473.html

一、标题/缩略图样式

1.添加标题列表样式的相关文章
WordPress代码实现相关文章的几种方法

这种相关文章的获取思路是:Tags标签相关>同分类下文章,也就是说,先获取标签相同的文章,如果还达不到数量,就调用该分类下的文章补足。

将下面的代码添加到 single.php 要显示相关文章的位置即可:

<h3>相关文章h3>
<ul class="related_posts">

$post_num = 8;
$exclude_id = $post->ID;
$posttags = get_the_tags(); $i = 0;
if ( $posttags ) {
	$tags = ''; foreach ( $posttags as $tag ) $tags .= $tag->term_id . ',';
	$args = array(
		'post_status' => 'publish',
		'tag__in' => explode(',', $tags),
		'post__not_in' => explode(',', $exclude_id),
		'caller_get_posts' => 1,
		'orderby' => 'comment_date',
		'posts_per_page' => $post_num,
	);
	query_posts($args);
	while( have_posts() ) { the_post(); ?>
		<li><a rel="bookmark" href="" title="" target="_blank"> the_title(); ?>a>li>
	
		$exclude_id .= ',' . $post->ID; $i ++;
	} wp_reset_query();
}
if ( $i < $post_num ) {
	$cats = ''; foreach ( get_the_category() as $cat ) $cats .= $cat->cat_ID . ',';
	$args = array(
		'category__in' => explode(',', $cats),
		'post__not_in' => explode(',', $exclude_id),
		'caller_get_posts' => 1,
		'orderby' => 'comment_date',
		'posts_per_page' => $post_num - $i
	);
	query_posts($args);
	while( have_posts() ) { the_post(); ?>
		<li><a rel="bookmark" href=""  title="" target="_blank"> the_title(); ?>a>li>
	 $i++;
	} wp_reset_query();
}
if ( $i  == 0 )  echo '
没有相关文章!
';
?>
ul>

PS:第四行$post_num = 8;表示显示8篇文章,请根据自己的需要修改。显示样式需要自己写css,可以参考一下下面的:

.related_posts{margin-top:5px;margin-left:10px;margin-bottom:20px;height:150px;list-style-position: inside;}
.related_posts li{margin-left:20px;color:#444;list-style:circle;font-size:14px;line-height:26px;padding:0 0 0 5px;float:left;width:45%;padding-right:9px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}
2.添加含缩略图的相关文章
WordPress代码实现相关文章的几种方法

1)在主题的 functions.php 的最后一个 ?> 前添加下面的代码:

//添加特色缩略图支持
if ( function_exists('add_theme_support') )add_theme_support('post-thumbnails');
 
//输出缩略图地址 From wpdaxue.com
function post_thumbnail_src(){
    global $post;
	if( $values = get_post_custom_values("thumb") ) {	//输出自定义域图片地址
		$values = get_post_custom_values("thumb");
		$post_thumbnail_src = $values [0];
	} elseif( has_post_thumbnail() ){    //如果有特色缩略图,则输出缩略图地址
        $thumbnail_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'full');
		$post_thumbnail_src = $thumbnail_src [0];
    } else {
		$post_thumbnail_src = '';
		ob_start();
		ob_end_clean();
		$output = preg_match_all('//i', $post->post_content, $matches);
		$post_thumbnail_src = $matches [1] [0];   //获取该图片 src
		if(empty($post_thumbnail_src)){	//如果日志中没有图片,则显示随机图片
			$random = mt_rand(1, 10);
			echo get_bloginfo('template_url');
			echo '/images/pic/'.$random.'.jpg';
			//如果日志中没有图片,则显示默认图片
			//echo '/images/default_thumb.jpg';
		}
	};
	echo $post_thumbnail_src;
}

PS:上面的代码主要是获取图片链接,获取的顺序是:

自定义字段为:thumb 的图片>特色缩略图>文章第一张图片>随机图片/默认图片;

随机图片:请制作10张图片,放在现用主题文件夹下的 images/pic/ 目录,图片为jpg格式,并且使用数字 1-10命名,比如 1.jpg;

如果你不想用随机图片,请将 倒数第5行 前面的“//”去掉,然后给 倒数第7、9行 前面添加“//”注销,并且在现用主题的 /images/ 目录下添加一张名字为 default_thumb.jpg 的默认图片,这样,就会显示默认图片。

2)将下面的代码添加到 single.php 要显示相关文章的位置:

<h3>相关文章h3>
<ul class="related_img">

$post_num = 4;
$exclude_id = $post->ID;
$posttags = get_the_tags(); $i = 0;
if ( $posttags ) {
	$tags = ''; foreach ( $posttags as $tag ) $tags .= $tag->term_id . ',';
	$args = array(
		'post_status' => 'publish',
		'tag__in' => explode(',', $tags),
		'post__not_in' => explode(',', $exclude_id),
		'caller_get_posts' => 1,
		'orderby' => 'comment_date',
		'posts_per_page' => $post_num
	);
	query_posts($args);
	while( have_posts() ) { the_post(); ?>
		<li class="related_box"  >
		<div class="r_pic">
		<a href="" title="" target="_blank">
		<img src="" alt="" class="thumbnail" />
		a>
		div>
		<div class="r_title"><a href="" title="" target="_blank" rel="bookmark"> the_title(); ?>a>div>
		li>
	
		$exclude_id .= ',' . $post->ID; $i ++;
	} wp_reset_query();
}
if ( $i < $post_num ) {
	$cats = ''; foreach ( get_the_category() as $cat ) $cats .= $cat->cat_ID . ',';
	$args = array(
		'category__in' => explode(',', $cats),
		'post__not_in' => explode(',', $exclude_id),
		'caller_get_posts' => 1,
		'orderby' => 'comment_date',
		'posts_per_page' => $post_num - $i
	);
	query_posts($args);
	while( have_posts() ) { the_post(); ?>
	<li class="related_box"  >
		<div class="r_pic">
		<a href="" title="" target="_blank">
		<img src="" alt="" class="thumbnail" />
		a>
		div>
		<div class="r_title"><a href="" title="" target="_blank" rel="bookmark"> the_title(); ?>a>div>
	li>
	 $i++;
	} wp_reset_query();
}
if ( $i  == 0 )  echo '
没有相关文章!
';
?>
ul>

PS:第四行$post_num = 4; 表示调用4篇文章,请根据自己需要修改。css样式自己写,也可参考一下:

.related_posts{margin-top:5px;}
.related_img{width:600px;height:210px;}
.related_box{float:left;overflow:hidden;margin-top:5px;width:148px;border-right:1px #eee solid}
.related_box:hover{background:#f9f9f9}
.related_box .r_title{width:auto;height:72px;font-weight:400;font-size:14px;margin:0 10px;overflow:hidden;}
.related_box .r_pic{margin:6px}
.related_box .r_pic img{width:130px;height:100px;border:1px  solid #e1e1e1;background:#fff;padding:2px}

二、五种不同添加(仅标题)方法

1、标签相关

首先获取文章的所有标签,接着获取这些标签下的 n 篇文章,那么这 n 篇文章就是与该文章相关的文章了。现在可以见到的WordPress相关文章插件都是使用的这个方法。下面是实现的代码:

"tags_related">

global $post;
$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="" rel="bookmark" title=""> the_title(); ?>a>li>

    }
  }
  else {
    echo '
* 暂无相关文章
';
  }
  wp_reset_query(); 
}
else {
  echo '
* 暂无相关文章
';
}
?>
ul>

使用说明:"不包括的分类ID" 指的是相关文章不显示该分类下的文章,将同行的 NULL 改成文章分类的ID即可,多个ID就用半角逗号隔开。因为这里限制只显示6篇相关文章,所以不管给 query_posts() 的参数 tag__in 赋多少个值,都是只显示一个标签下的 6 篇文章,除非第一个标签有1篇,第二个标签有2篇,第三个有3篇。。。。。。所以如果这篇文章有多个标签,那么我们采取的做法是随机获取一个标签的id,赋值给 tag__in 这个参数,获取该标签下的6篇文章。

2、分类相关

本方法是通过获取该文章的分类id,然后获取该分类下的文章,来达到获取相关文章的目的。

"cat_related">

global $post;
$cats = wp_get_post_categories($post->ID);
if ($cats) {
    $args = array(
          'category__in' => array( $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="" rel="bookmark" title=""> the_title(); ?>a>li>

    }
  } 
  else {
    echo '
* 暂无相关文章
';
  }
  wp_reset_query(); 
}
else {
  echo '
* 暂无相关文章
';
}
?>
ul>
方法三:标签相关,SQL获取

获取相关文章的原理与方法一相似,不过在获取文章的时候是以SQL语句来直接读取数据库,从而随机获取6篇相关文章记录,而不是WordPress的函数query_posts()。

"tags_related">

global $post, $wpdb;
$post_tags = wp_get_post_tags($post->ID);
if ($post_tags) {
    $tag_list = '';
    foreach ($post_tags as $tag) {
        // 获取标签列表
        $tag_list .= $tag->term_id.',';
    }
    $tag_list = substr($tag_list, 0, strlen($tag_list)-1);

    $related_posts = $wpdb->get_results("
        SELECT DISTINCT ID, post_title
        FROM {$wpdb->prefix}posts, {$wpdb->prefix}term_relationships, {$wpdb->prefix}term_taxonomy
        WHERE {$wpdb->prefix}term_taxonomy.term_taxonomy_id = {$wpdb->prefix}term_relationships.term_taxonomy_id
        AND ID = object_id
        AND taxonomy = 'post_tag'
        AND post_status = 'publish'
        AND post_type = 'post'
        AND term_id IN (" . $tag_list . ")
        AND ID != '" . $post->ID . "'
        ORDER BY RAND()
        LIMIT 6");
        // 以上代码中的 6 为限制只获取6篇相关文章// 通过修改数字 6,可修改你想要的文章数量

    if ( $related_posts ) {
        foreach ($related_posts as $related_post) {
?><li><a href="ID); ?>" rel="bookmark" title="post_title; ?>"> echo $related_post->post_title; ?>a>li>
   } 
    }
    else {
      echo '
暂无相关文章
';
    } 
}
else {
  echo '
暂无相关文章
';
}
?>
ul>
方法四:分类相关,SQL获取

获取相关文章的原理与方法二相似,不过在获取文章的时候是以SQL语句来直接读取数据库,从而随机获取6篇相关文章记录,而不是WordPress的函数query_posts()。

"cat_related">

global $post, $wpdb;
$cats = wp_get_post_categories($post->ID);
if ($cats) {
  $related = $wpdb->get_results("
  SELECT post_title, ID
  FROM {$wpdb->prefix}posts, {$wpdb->prefix}term_relationships, {$wpdb->prefix}term_taxonomy
  WHERE {$wpdb->prefix}posts.ID = {$wpdb->prefix}term_relationships.object_id
  AND {$wpdb->prefix}term_taxonomy.taxonomy = 'category'
  AND {$wpdb->prefix}term_taxonomy.term_taxonomy_id = {$wpdb->prefix}term_relationships.term_taxonomy_id
  AND {$wpdb->prefix}posts.post_status = 'publish'
  AND {$wpdb->prefix}posts.post_type = 'post'
  AND {$wpdb->prefix}term_taxonomy.term_id = '" . $cats[0] . "'
  AND {$wpdb->prefix}posts.ID != '" . $post->ID . "'
  ORDER BY RAND( )
  LIMIT 6");

  if ( $related ) {
      foreach ($related as $related_post) {
?><li>* <a href="ID); ?>" rel="bookmark" title="post_title; ?>"> echo $related_post->post_title; ?>a>li>

    } 
  }
  else {
    echo '
* 暂无相关文章
';
  } 
}
else {
  echo '
* 暂无相关文章
';
}
?>
ul>
方法五:作者相关

该方法是获取该文章作者的其他文章来充当相关文章,代码如下:

"author_related">
global $post;
  $post_author = get_the_author_meta( 'user_login' );
  $args = array(
        'author_name' => $post_author,
        'post__not_in' => array($post->ID),
        'showposts' => 6,               // 显示相关文章数量'orderby' => date,          // 按时间排序'caller_get_posts' => 1
    );
  query_posts($args);

  if (have_posts()) {
    while (have_posts()) {
      the_post(); update_post_caches($posts); ?><li>* <a href="" rel="bookmark" title=""> the_title(); ?>a>li>

    }
  }
  else { 
    echo '
* 暂无相关文章
';
  }
  wp_reset_query();
?>
ul>
插件

All in One WP Migration - 多合一迁移wordpress插件

2019-10-17 21:03:26

国外主题

Malina - 个人WordPress博客主题

2020-6-30 23:42:00

⚠️
Npcink上的部份代码及教程来源于互联网,仅供网友学习交流,若您喜欢本文可附上原文链接随意转载。
无意侵害您的权益,请发送邮件至 1355471563#qq.com 或点击右侧 私信:Muze 反馈,我们将尽快处理。
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索