WordPress 代码实现相关文章(列表模式)功能

之前分享的相关文章代码化功能是仿无觅的图文模式,现在分享的一个是文章列表陈列模式。代码最初来自 Willin Kan,经过zwwooooo 的修改优化。不得不说,这个代码所实现的相关文章的相关度非常高(优先通过 Tags 标签相关,之后是同分类下文章,排除当前文章)。要是能修改一下能用在图文模式就完美了。

WordPress 代码实现相关文章(列表模式)功能代码

在你的主题需要显示效果文章的地方加入以下代码:

<h3>Related Posts</h3>
<ul>
<?php
$post_num = 5; // 數量設定.
$exclude_id = $post->ID; // 單獨使用要開此行 //zww: edit
$posttags = get_the_tags(); $i = 0;
if ( $posttags ) {
	$tags = ''; foreach ( $posttags as $tag ) $tags .= $tag->term_id . ','; //zww: edit
	$args = array(
		'post_status' => 'publish',
		'tag__in' => explode(',', $tags), // 只選 tags 的文章. //zww: edit
		'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="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
	<?php
		$exclude_id .= ',' . $post->ID; $i ++;
	} wp_reset_query();
}
if ( $i < $post_num ) { // 當 tags 文章數量不足, 再取 category 補足.
	$cats = ''; foreach ( get_the_category() as $cat ) $cats .= $cat->cat_ID . ',';
	$args = array(
		'category__in' => explode(',', $cats), // 只選 category 的文章.
		'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="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
	<?php $i++;
	} wp_reset_query();
}
if ( $i  == 0 )  echo '<li>没有相关文章!</li>';
?>
</ul>

具体的css样式需要自己来啦。

相关文章:《WordPress纯代码高仿 无觅相关文章 图文模式功能

评分:
当前平均分 0.00 (0%) - 0 个投票
3 条 评论
  1. 我的http://www.caifan.org/535.html

    10年前 回复
  2. 你好,麻烦你一下,我的文章底部添加了一个相关文章的代码,就是多说
    上头的那一段请问如何设置成两列显示,请大侠给指点代码分享一下
    http://www.caifan.org/535.html

    10年前 回复
    • CSS 的问题,具体直接折腾吧

      10年前 回复
发表评论