Hide featured image if it’s in the post

I’ve been running a photoblog at inphotos.org since 2005 on WordPress. (And thanks to writing this I noticed it’s 15 years old today!)

In that time WordPress has changed dramatically. At first I used Flickr to host my images, but after a short time I hosted the images myself. (Good thing too since Flickr limited free user accounts to 1000 images, so I wrote a script to download the Flickr images I used in posts.)

For quite a long time I used the featured image instead of inserting the image into the post content, but then about two years ago I went back to inserting the photo into the post. Unfortunately that meant the photo was shown twice, once as a featured image, and once in the post content.

The last theme I used supported custom post types, one of which was a photo type that displayed the featured image but hid the post content. It was an ok compromise, but not perfect.

Recently I started using Twenty Twenty, but after 15 years I had a mixture of posts with:

  • Featured image with no image in the post.
  • Featured image with the same image in the post.

I knew I needed something more flexible. I wanted to hide the featured image if it also appeared in the post content. I procrastinated and never got around to it until this evening when I discovered it was actually quite easy.

Copy the following code into the function.php of your child theme and you’ll be all set! It relies on you having unique filenames for your images. If you don’t then remove the call to basename(), and that may help.

function maybe_remove_featured_image( $html ) {
        if ( $html == '' ) {
                return '';
        }
        $post = get_post();
        $post_thumbnail_id = get_post_thumbnail_id( $post );
        if ( ! $post_thumbnail_id ) {
                return $html;
        }

        $image_url = wp_get_attachment_image_src( $post_thumbnail_id );
        if ( ! $image_url ) {
                return $html;
        }

        $image_filename = basename( parse_url( $image_url[0], PHP_URL_PATH ) );
        if ( strpos( $post->post_content, $image_filename ) ) {
                return '';
        } else {
                return $html;
        }
}
add_filter( 'post_thumbnail_html', 'maybe_remove_featured_image' );

The post_thumbnail_html filter acts on the html generated to display the featured image. My code above gets the filename of the featured image, checks if it’s in the current post and if it is returns a blank string. Feedback welcome if you have a better way of doing this!

Leave a Reply

%d bloggers like this:

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close