WordPress: handling post thumbnails

Some WordPress themes don't support featured images and post thumbnails. Other themes proudly claim to support them, but when you try to display your images the functionality provided is somewhat broken. So the best thing you can do is to implement this feature by yourself. Let's see how.

Step 1: add post thumbnails support

Open the functions.php file of your theme and add this code (create a brand new file named functions.php if it doesn't exist). Don't forget to put your code between the PHP tags (<?php ... ?>):

if (function_exists('add_theme_support')) {
    add_theme_support('post-thumbnails');
    add_image_size('index-categories', 190, 150, true);
}

The numeric values specify the width and height of your thumbnail in pixels. You can modify such values to suit your needs.

Step 2: insert the thumbnail into the post content

Insert the following code after the previous code:

function insert_featured_image($content) {
 
global $post;
 
$original_content = $content;

if(is_home()) {
 
    if ( current_theme_supports( 'post-thumbnails' ) ) {

 
       
            $content = the_post_thumbnail('index-categories');
            $content .= $original_content;

	
       
 
    }
}
    return $content;
}
 
add_filter( 'the_content', 'insert_featured_image' );

We've just inserted our thumbnails only in the home page just before the actual content of the post. If you want your images to appear on all sections, just remove the conditional if(is_home()) {...} block.

Optional: remove the very first image of your posts

If you have already inserted an image (e.g. a floated one) in the very first paragraph of your post and you don't want that your floated image and the thumbnail image appear together on the same post, you can remove the first image, as shown below:

function remove_first_image($content) {

    global $post;


    if(is_home()) {

      $content = preg_replace('/<p><img[^>]*\/>/', '<p>', $content);
      

    }

    return $content;

}

add_filter( 'the_content', 'remove_first_image' );

As said above, if you want to extend this feature to all the sections of your WordPress site, just remove the conditional if(is_home()) {...} block. Further, you can change this check to test whether you're viewing a single post, a category and so on by using other conditional WordPress functions such as is_singular() or is_category().

Comments are closed.