This question is very similar to the one below however it requires a different solution.

Don't display html if custom field is empty

I'm using the plugin Related Posts Thumbnails but i'm using the template tag in my template file to display related products.

<?php get_related_posts_thumbnails(); ?>

Plugin Source

I've got this contained inside of a div with a title so the output looks a bit better. However if there isn't any related products i need it to hide the div otherwise it just displays an empty area.

This is the code i'm using.

<div id="relatedproducts">
    <h1>Related Products</h1>
    <?php get_related_posts_thumbnails(); ?></div>

Is it possible to not show this div if the function returns no related products?


global $related_posts_thumbnails;
if ($related_posts_thumbnails->get_html()) { ?>

    <div id="relatedproducts">
        <h1>Related Products</h1>
        <?php get_related_posts_thumbnails() ?>

<?php } ?>

A quick look at the get_related_posts_thumbnails() shows that it is simply echoing the HTML returned from the get_html() method of the $related_posts_thumbnails object. By checking the returned HTML first, you can make sure it is not an empty string (or any falsy value).

Note for the plugin author: picking the name get_related_posts_thumbnails() and making it echo the output is quite unintuitive. Other WordPress functions use the get_ prefix for functions that return data, and leave it out to echo it. For example: get_bloginfo('url') vs bloginfo('url').

  • I've tried this and it seems to work perfectly. Thanks a lot. – Corbula Dec 12 '11 at 15:50

Looks like the plugin's function echos the output and does not return it. But the plugin has a shortcode, which you can use to get what you want.

$thumbs = do_shortcode('[related-posts-thumbnails]');
if(strlen($thumbs) > 0)
    <div id="relatedproducts">
    <h1>Related Products</h1>
        <?php echo $thumbs; ?>
<?php }

Try this and let me know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.