I did a search not only on Google but other places, including here and cannot find anything to help with this issue.
Here is the problem. I have a related posts snippet based on tags instead of categories, that I use in WordPress themes and I have been using it for quite some time and it works really well. Here is is:
$tags = wp_get_post_tags($post->ID);
$tagIDs = array();
if ($tags) {
$tagcount = count($tags);
for ($i = 0; $i < $tagcount; $i++) {
$tagIDs[$i] = $tags[$i]->term_id;
}
$args=array(
'tag__in' => $tagIDs,
'post__not_in' => array($post->ID),
'showposts'=>mytheme_option( 'related_count' ),
'ignore_sticky_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<h4>'. __('Other Posts You May Be Interested In', "themename"). ':</h4><ul>';
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li class="imglink">
<!-- post loop stuff goes here -->
</li>
<?php endwhile;
echo '</ul>';
}
else {
echo '<h4>'. __('Other Posts You May Be Interested In', "themename"). ':</h4>
'. __('<p>There are no related posts at this time.</p>', "themename"). '';
}
}
$post = $original_post;
wp_reset_query();
Like I said it works really well. If posts have the same tag, then this shows:
Other Posts you May Be Interested In:
posts with the same tag get displayed
BUT here is the problem: If a single post is given a tag and no other posts have that same tag, this is what shows:
Other posts you may be interested in: There are no related posts at
this time.
Now if a post is not assigned a tag, absolutely nothing shows. The div where related posts are supposed to display is empty but it should say there are no related posts.
I have looked for a solution and tried many different things to get this corrected but I can’t seem to get my head around it. Can someone assist me in getting:
Other posts you may be interested in: There are no related posts at
this time.
to display if a post has no tag. Any help is greatly appreciated and thank you very much in advance.
I believe the problems comes from the conditional towards the top of the function:
If no tags are found for the post, it skips all your code and doesn’t render anything. The else statement at the bottom of your code is only executed if there are tags for the current post, but no other posts contain that tag.
Edit with example as requested – you need to have 2 else conditions which echo out the no posts content, one for if there are no tags and one for if there are tags but posts were not found:
That should do it. I would maybe suggest wrapping the content into a function, however. Then you could just echo out the no post content at the end of the function, and ‘return’ if posts were found. Then you wouldn’t be repeating yourself.