Question

The following code shows related posts by tags, I want to hide it if there are no tags!

<?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();
?>

Thanks in advance.

Was it helpful?

Solution

I believe your if statement involving $tags is causing "Related Posts" to show.

"if ($tags)" is returning true because even if a post doesn't have tags wp_get_posts_tags() still returns an array, not null or 0.

Delete

echo 'Related Posts';

from it's current location and replace it as shown here:

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();
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top