如果没有标签,Wordpress隐藏相关帖子

时间:2014-01-31 01:52:55

标签: wordpress posts

以下代码按标签显示相关帖子,如果没有标签,我想隐藏它!

<?php
//for use in the loop, list 5 post titles related to first tag on current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo 'Related Posts';
$first_tag = $tags[0]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'showposts'=>5,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
<?php
endwhile;
}
}
wp_reset_query();
?>

提前致谢。

1 个答案:

答案 0 :(得分:0)

我相信你的涉及$ tag的if语句会导致显示“相关帖子”。

“if($ tags)”返回true,因为即使帖子没有标签,wp_get_posts_tags()仍会返回一个数组,而不是null或0。

删除

echo 'Related Posts';

从它的当前位置并替换它,如下所示:

if( $my_query->have_posts() ) {
   echo 'Related Posts'; // Insert it here.
   while ($my_query->have_posts()) : $my_query->the_post(); ?>
     <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
   <?php
   endwhile;
   }
}
wp_reset_query();
?>
相关问题