以前介绍过一个“不用插件实现调用 WordPress 随机相关文章”的方法,不过,那个相关文章的调用代码是基于所有文章的;而下面介绍的这个代码虽然也是调用 WordPress 随机相关文章,但这个是基于同一个分类的。

使用也非常简单,把下面的代码添加到 single 模板或 sidebar 模板文件中合适的位置即可。其中,“showposts”后的数字“10”就是显示的随机相关文章的数量,根据自己需要可以自行修改。

<ul>
<?php
$cat = get_the_category();
foreach($cat as $key=>$category){
$catid = $category->term_id;
}
$args = array('orderby' => 'rand','showposts' => 10,'cat' => $catid );
$query_posts = new WP_Query();
$query_posts->query($args);
while ($query_posts->have_posts()) : $query_posts->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile;?>
</ul>