• Hello, I’ve been trying to get an If/Else statement working for post thumbnails for a while now. I think I have the code write at this point, but it’s still not working and I’m starting to think there may be a deeper problem.

    A while ago my site had some issues with the host and the DB seems to have been hosed a bit. I lost about 400 posts, luckily I regularly back things up so I was able to restore them. The problem is, while the images in the actual post are there, the Featured Image is gone, and when looking through the Insert Media screen, none of them are there, even the ones displaying in the post. The post just happens to have the full URL to the image so it can find it.

    Anyway, since there are so many posts, I wanted to setup an IF/Else statement that will display the Featured Image if it exists, or display a standard image if it doesn’t. Here is the code I’m using right now that doesn’t work.

    <?php
    if ( has_post_thumbnail() ) { ?>
        <p class="image"><a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>"><?php  the_post_thumbnail( 'recent' );  ?></a></p>
    <?php } else{ ?>
        <img src="https://www.one-quest.com/wp-content/themes/One-Quest3/images/logo.png" width="64" height="64" alt="<?php the_title(); ?>" />
    <?php } ?>

    I starting to wonder if maybe somewhere in the database or something the effected posts still have a link for a featured image being true. I’m not a database person though so I’m not even sure if that’s possible or if there is anyway to clear it without also clearing all the working posts.

    Anyone have any tips or thoughts I could try?

Viewing 1 replies (of 1 total)
  • It sounds like the values are still in the database, so has_post_thumbnail will still return true. Eventually, I’d suggest getting a list of all featured images from the database and cleaning up the ones that don’t exist. But, adding onto your idea, this should check if the featured image URL returns a 404 (doesn’t exist) or not (warning, untested code ahead):

    <?php
    $file = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
    $file_headers = @get_headers($file);
    if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
        $exists = false;
    }
    else {
        $exists = true;
    }
    
    if ( has_post_thumbnail() && $exists ) { ?>
        <p class="image"><a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>"><?php  the_post_thumbnail( 'recent' );  ?></a></p>
    <?php } else{ ?>
        <img src="https://www.one-quest.com/wp-content/themes/One-Quest3/images/logo.png" width="64" height="64" alt="<?php the_title(); ?>" />
    <?php } ?>
Viewing 1 replies (of 1 total)
  • The topic ‘Post Thumbnail IF/ELSE issue’ is closed to new replies.