wordpress一般相关文章都是根据标签、分类等方式调取但是很多没有查询到相关符合的就输出暂无文章了,今天咱们说说根据本文的标签读取相关文章,如果没有就随机读取,根据wp_get_post_tags来读取:
<?php
global $post;
$post_tags = wp_get_post_tags($post->ID);
foreach ($post_tags as $tag) {
// 获取标签列表
$tag_list[] .= $tag->term_id;
}
// 随机获取标签列表中的一个标签
$post_tag = $tag_list[ mt_rand(0, count($tag_list) - 1) ];
if($post_tags){
// 该方法使用 query_posts() 函数来调用相关文章,以下是参数列表
$args = array(
'tag__in' => array($post_tag),
'category__not_in' => array(NULL), // 不包括的分类ID
'post__not_in' => array($post->ID),
'showposts' => 2, // 显示相关文章数量
'caller_get_posts' => 1
);
}else{
$args = array(
'orderby' => rand,
'category__not_in' => array(NULL), // 不包括的分类ID
'post__not_in' => array($post->ID),
'showposts' => 2, // 显示相关文章数量
'caller_get_posts' => 1
);
}
query_posts($args);
if (have_posts()) {
while (have_posts()) {
the_post(); update_post_caches($posts); ?>
<div class="result f s0">
<h3 class="c-title">
<a href="<?php the_permalink(); ?>" target="_blank"><?php the_title(); ?></a>
</h3>
<div>
<div class="c-content">
<div class="c-abstract"><?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 200,"..."); ?></div>
<div>
<span class="c-showurl"><?php the_permalink(); ?> <?php the_time('Y-n-j'); ?> </span>
</div>
</div>
</div>
</div>
<?php
}
}
wp_reset_query();
?>

