Support » Developing with WordPress » How to do a ‘real’ “has image” check

  • Resolved MVertruger


    This question is probably for advanced WordPress developers.

    I have a dilemma where image thumbnails are being detected as “true” by has_post_thumbnail() even though the image is actually non-existent in the uploads/ folder.

    This happens when I use the WordPress importer tool, and the exported process fails to do the: “download post attachments(?)” [paraphrasing].

    So say, if you have this generic structure for displaying the_post_thumbnail():

    if (has_post_thumbnail()) {//this functions checks the database *instead* of the actual presence of the image in the uploads/ folder ?>
          <a href="<?php the_permalink(); ?>" target="_top" title="<?php the_title(); ?>" rel="bookmark" role="banner">
            <?php the_post_thumbnail(); ?>
        <?php } else { //it's supposed to show a "default" image, but instead, it *blanks* ?>
          <img src="<?= THE_BLOG_THEME_DIR; ?>/img/fig-<?= rand(1,3); ?>-def.jpg" alt="<?php the_title(); ?>" />
        <?php } ?>

    Because on the imported data of the post says that the post “has a thumbnail” – the has_post_thumbnail() functions triggers as true – but the image is *not* or is in a wrong directory on the new WordPress installation – the image doesn’t show up.

    I’m okay with the image not showing up, but I’d like my conditional to show up with a generic image instead of it triggering a “true” boolean output when it’s supposed to be false.

    Somewhere out there, this problem has been worked around – but I’ve been searching and no solutions yet.

    There are probably plugins there that fix database-to-image location relationships, but I haven’t seen them yet (recommend please).


    • This topic was modified 3 years, 9 months ago by MVertruger. Reason: might mislead people if I say, "has_image()" thinking I don't know that there's no such function - I'm just making a reference
Viewing 3 replies - 1 through 3 (of 3 total)
  • I had a similar problem once.

    I worked it out by using the function get_the_post_thumbnail instead of the_post_thumbnail, apparently the the_post_thumbnail brings a place holder even when there is no image actually.

    I hope this can be useful somehow, however may the other people of the community share other ideas to help you out.

    Andrew Nevins


    WCLDN 2018 Contributor | Volunteer support

    In my experience, when images are attached to the page but in some way are invalid I tackle this with JS to provide a fallback.

    Thread Starter MVertruger


    This works:

    $checkThumbnail = get_the_post_thumbnail_url();
      if (has_post_thumbnail() && $checkThumbnail) {
      } else {
        // static image

    Thanks Mateus

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘How to do a ‘real’ “has image” check’ is closed to new replies.