WordPress代码实现相关文章

例如我博客使用的默认twenty ten 主题

loop-single.php里边找到<?php the_content(); ?>   在后边加上相关文章代码:

<h3>相关文章</h3>

<ul>

<?php

$all_tags = wp_get_post_tags($post->ID);

if ($all_tags) {

$tag_list = ”;

foreach ($all_tags as $tag)

{

// 获取标签列表

$tag_list .= $tag->term_id.’,’;

}

$tag_list = substr($tag_list, 0, strlen($tag_list)-1);

 

$related_posts = $wpdb->get_results(”

SELECT post_title, ID

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=”<?php echo get_permalink($related_post->ID); ?>” rel=”bookmark” title=”<?php echo $related_post->post_title; ?>”>

<?php echo $related_post->post_title; ?></a></li>

<?php  } } else { ?>

<li>暂无相关文章</li>

<?php } } ?>

</ul>

发表评论

邮箱地址不会被公开。 必填项已用*标注