multiple-featured-images-header

How to add Multiple Featured Images in WordPress

The post thumbnails feature aka. Featured Image was added to WordPress back in version 2.9 and made it significantly easier for users to associate images with posts or pages. Prior to that we we had to upload an image, copy the url for the image and add that as a custom field if we wanted to do something similar, which is ok when you know how to do it yourself but less than ideal when having to explain the process to clients or other authors. The post thumbnails feature allows you to easily set a single “Featured Image” for a post or page via a separate meta box in the WordPress admin. You simply click on the “Set featured image” link, open up the image dialog, upload or select an image then click the “use as featured image” link.

This works fine for the vast majority of cases but sometimes it would be great to have have more than one image for a post. For example if you have a folio section or a product where you may want to have multiple images. I tried searching for “mulitple post thumbnails”, “multiple featured images” and so on but most of the “solutions” were mainly about looping through all post attachments and displaying these. This can work in some instances but it didn’t provide as much control as I wanted and if you happened to have other images in the post then these would also be displayed.

Eventually I came across a plugin called Multiple Post Thumbnails and decided to tweak that slightly and integrate it directly into my theme instead of using it as a separate plugin. This is how I did it.

Adding support for post thumbnails in your WordPress theme

First things first, before you start adding support for multiple post thumbnails you need to ensure you have the basic post thumbnails enabled for your theme. Check your functions.php file and make sure the following line is present, if not add it in.

 add_theme_support( 'post-thumbnails' ); 

You can also define additional sizes for your post thumbnails.

// Add Custom image sizes
// Note: 'true' enables hard cropping so each image is exactly those dimensions and automatically cropped
add_image_size( 'feature-image', 960, 500, true ); 
add_image_size( 'medium-thumb', 300, 156, true );
add_image_size( 'small-thumb', 75, 75, true );

Adding the files and support for multiple post thumbnails to your theme

  1. Download the files for the Multiple Post Thumbnails Plugin to your computer
  2. Unzip the files and copy them to a sub-directory in your theme file. There are only two files you will need multi-post-thumbnails.php and multi-post-thumbnails-admin.js. In my case i’ve placed the PHP file in a library sub-directory in my theme and the JavaScript file in a sub-directory called js inside library.
    > theme-name
       > library
         - multi-post-thumbnails.php
         > js
           - multi-post-thumbnails-admin.js
    
  3. Once that’s done you need to make a small tweak to the multi-post-thumbnails.php file.
    From this (line 143)

    public function enqueue_admin_scripts() {
        wp_enqueue_script("featured-image-custom", plugins_url(basename(dirname(__FILE__)) . '/js/multi-post-thumbnails-admin.js'), array('jquery'));
    }
    

    To this

    public function enqueue_admin_scripts() {
        $template_url = get_bloginfo('template_url') . '/js/multi-post-thumbnails-admin.js';
        wp_enqueue_script("featured-image-custom",  $template_url, array('jquery'));
    }
    
  4. Then go back to your functions.php file and add the following.
    // Load external file to add support for MultiPostThumbnails. Allows you to set more than one "feature image" per post.
    require_once('library/multi-post-thumbnails.php');
    

    It’s usually a good idea to keep these inclusions at the beginning of your functions.php file so they are included before you try to use any of the functions they add.

  5. You then need to define some additional post thumbnails and specify which post types they should apply to. The default would be ‘post’ but in my case I had created a custom post type called folio where I’d added 4 extra post thumbnails for a total of up to 5 featured image for each folio item. To do this add the following in functions.php just after the add_image_size entries mentioned above.
    	// Define additional "post thumbnails". Relies on MultiPostThumbnails to work
    	if (class_exists('MultiPostThumbnails')) {
    		new MultiPostThumbnails(array(
    			'label' => '2nd Feature Image',
    			'id' => 'feature-image-2',
    			'post_type' => 'folio'
    			)
    		);
    		new MultiPostThumbnails(array(
    			'label' => '3rd Feature Image',
    			'id' => 'feature-image-3',
    			'post_type' => 'folio'
    			)
    		);
    		new MultiPostThumbnails(array(
    			'label' => '4th Feature Image',
    			'id' => 'feature-image-4',
    			'post_type' => 'folio'
    			)
    		);
    		new MultiPostThumbnails(array(
    			'label' => '5th Feature Image',
    			'id' => 'feature-image-5',
    			'post_type' => 'folio'
    			)
    		);		
    	
    	};
    

That’s it, you’ve now added support for mulitple post thumbnails for your post or custom post type and you should see several “Featured Images” boxes in your admin screen. This is what mine looked like.


Displaying the post thumbnails in your WordPress posts

So now you’ve (hopefully) got the admin part working and are able to add multiple post thumbnails to your posts, but you also need to output these in your post or page template. Continuing on my folio concept I wanted to output these images to use in a JavaScript slider. I happened to be using the Nivo Slider at the time but it doesn’t really matter what you use, you’ll just need to tweak the HTML output to match what your slider expects.

This is where the added control of the featured images comes in handy over just scanning through attachments, you might find it easier just to upload a bunch of images and let WordPress use all of the attachments but I needed control over the order and also wanted the freedom to add more images into the description of a folio item without having to worry about it ending up in the slider.

Here’s the PHP code. I’ll try to explain a bit more how it works. The listing is done in two steps. First we show the standard featured image, we then loop through and display all the extra featured images. Because I wanted to use the Nivo slider thumbnail view I had to include a REL attribute with the url for the thumbnail version of the image. After a lot of searching I finally figured that I could add an array of attributes when calling the_post_thumbnail() and this also worked for wp_get_attachment_image() which I ended up having to use instead of the standard MultiPostThumbnails::the_post_thumbnail().

<div id="slider">	         
    <?php	
        // Checks if post has a feature image, grabs the feature-image and outputs that along with thumbnail SRC as a REL attribute 
        if (has_post_thumbnail()) { // checks if post has a featured image and then outputs it. 	
            $image_id = get_post_thumbnail_id ($post->ID );  
            $image_thumb_url = wp_get_attachment_image_src( $image_id,'small-thumb');  								
            $attr = array(
                'class'	=> "folio-sample",									
                'rel' => $image_thumb_url[0], // REL attribute is used to show thumbnails in the Nivo slider, can be skipped if you don't want thumbs or using other slider
            );
            the_post_thumbnail ('feature-image', $attr);											
        }
        if (class_exists('MultiPostThumbnails')) {								
        // Loops through each feature image and grabs thumbnail URL
        $i=1;
            while ($i<=5) {
                $image_name = 'feature-image-'.$i;  // sets image name as feature-image-1, feature-image-2 etc.
                if (MultiPostThumbnails::has_post_thumbnail('folio', $image_name)) { 
                    $image_id = MultiPostThumbnails::get_post_thumbnail_id( 'folio', $image_name, $post->ID );  // use the MultiPostThumbnails to get the image ID
                    $image_thumb_url = wp_get_attachment_image_src( $image_id,'small-thumb');  // define thumb src based on image ID
                    $image_feature_url = wp_get_attachment_image_src( $image_id,'feature-image' ); // define full size src based on image ID
                    $attr = array(
                        'class'	=> "folio-sample",      // set custom class
                        'rel' => $image_thumb_url[0],   // sets the url for the image thumbnails size
                        'src' => $image_feature_url[0], // sets the url for the full image size 
                    );																						
                    // Use wp_get_attachment_image instead of standard MultiPostThumbnails to be able to tweak attributes
                    $image = wp_get_attachment_image( $image_id, 'feature-image', false, $attr );                     
                    echo $image;
                }							
                $i++;
            }                            
        
        }; // end if MultiPostThumbnails 
     ?>
</div><!-- end #slider -->

Now all of this can be done a lot easier just using the standard call from the plugin e.g.

if (class_exists('MultiPostThumbnails') {
    if (MultiPostThumbnails::has_post_thumbnail('folio', 'feature-image-2')) {
        MultiPostThumbnails::the_post_thumbnail('folio', 'feature-image-2'); 
    }
    if (MultiPostThumbnails::has_post_thumbnail('folio', 'feature-image-3')) {
        MultiPostThumbnails::the_post_thumbnail('folio', 'feature-image-3'); 
    }
    if (MultiPostThumbnails::has_post_thumbnail('folio', 'feature-image-3')) {
        MultiPostThumbnails::the_post_thumbnail('folio', 'feature-image-3'); 
    }
}

However because I needed the extra control over the output of attributes I ended up having to do it a bit more complex. If you’re planning on using the featured images in a slider that requires specific classes, attributes or HTML structure then you may need to go down the same route I’ve done. Hopefully with the code above most of the hard work will be done for you already.

Final words

Well there you have it, if everything went well you should have a working post with multiple post thumbnails and a more elegant way of adding multiple feature images to your posts. If you’re doing work for clients I think this approach will be a bit more user friendly than trying to explain attachments or pasting in URLs into custom fields. The cool thing is that you can set featured images for completely different uses on the same post as well. They don’t need to be called feature images. If you’re doing a real estate web site you could have some images defined as interior, some for exterior and a separate one for floorplan which will give you the control needed to output the right images where needed. It also guides the authors to what they need to add.

Until WordPress 3.3 comes out and hopefully Plupload is integrated into the dashboard this is a pretty decent solution, at least compared to anything else I’ve seen so far.

51 thoughts on “How to add Multiple Featured Images in WordPress”

    1. There’s already a pretty good responsive slider out there called FlexSlider http://flex.madebymufffin.com/ the syntax is pretty similar and you just need to output each image for the slider in a list but other than that it would pretty much be the same.

      If you’re considering outputting different sized images depending on the resolution, then you could in theory setup a number of different image sizes for the feature images and grab the specific size of each as needed.

      You could then for example output the thumbnail and medium size or whatever as attributes or just hidden spans which you could then reference with the JavaScript and CSS to display the smaller sizes at different resolution break points.

  1. What an awesome post – great detailed instructions!

    Everything works until I try to add additional featured images:

    Warning: Cannot modify header information – headers already sent by (output started at ../wp-content/themes/organic_studio/functions.php:314) in /public_html/delandarch/wp-includes/pluggable.php on line 934

  2. Hello Lars,

    Thanks for the tutorial! Just remember on step 3, when you replace line 143… you must insure your JS file (multi-post-thumbnails-admin.js) is pointing correctly.

    Otherwise you will only be able to see the featured boxes, and will not be able to attach images.

  3. Very useful hack, although I am having a problem similar to Saki.

    When I try to assign a secondary featured image the media uploader box scrolls to the top and nothing happens. Both the js and php files are loading.

    I’d greatly appreciate any thoughts on how to troubleshoot this. Thanks!

    1. I had this problem too and fixed it by changing the following line of code in multi-post-thumbnails.php.

      $template_url = get_bloginfo(‘template_url’) . ‘/js/multi-post-thumbnails-admin.js’;

      $template_url = get_bloginfo(‘template_url’) . ‘/library/js/multi-post-thumbnails-admin.js’;

  4. an awesome work. I was looking days for set multiple featured images and no lucky. Finally I found this post and this exactly fulfilled my need.

    Thanks a lot for sharing this with us.

  5. Hope it’s not too late to ask for help, but how do I display a specific image of a post/page for let’s say the second featured image?

  6. Thanks for putting this online. I prefer to add the code myself instead of having a plugin run in the background, so this is perfect!

    Your time and skills are appreciated.

  7. Thank you so much for this method, this is exactly what I need.

    There is a bit of a bug in the code posted based on the directory structure you suggest earlier in the post.

    If you’ve put the MultiPostThumbnail files inside a “library” directory within the theme folder, you should change line 143 in the multi-post-thumbnails.php to


    public function enqueue_admin_scripts() {
    $template_url = get_bloginfo('template_url') . '/library/js/multi-post-thumbnails-admin.js';
    wp_enqueue_script("featured-image-custom", $template_url, array('jquery'));
    }

    This is because, although the multi-post-thumbnail.php file itself is within the library directory, the functions.php file which you include that file in is in the main theme directory.

  8. Hey, I hope you still read these comments.

    I’ve implemented your method and it works great, besides one thing: I want to resize the featured images in my template files.

    So, using your code above:

    if (class_exists(‘MultiPostThumbnails’)) {
    if (MultiPostThumbnails::has_post_thumbnail(‘folio’, ‘feature-image-2′)) {
    MultiPostThumbnails::the_post_thumbnail(‘folio’, ‘feature-image-2′);
    }
    }

    …how do I resize this image? I’ve tried using an array as I would normally – e.g.(‘folio’,'feature-image-2, array(100,100)) but this doesn’t work.

    Any advice? I don’t want to set the image size in functions because I want it different sizes for different circumstances.

    I’d really appreciate any help.

  9. For image sizes you would typically set those when you add thumbnail support for your theme. Whilst doing this you can also define any number of ‘thumbnail’ sizes.

    E.g.
    add_image_size( ‘feature-image’, 960, 500, true );
    add_image_size( ‘medium-thumb’, 300, 156, true );
    add_image_size( ‘small-thumb’, 75, 75, true );

    The examples above have true set for the crop parameter meaning a hard crop, if you leave this as false it will use a soft proportional crop.

    You can also set just one of the dimensions e.g. just height or just width and use soft cropping.

    Check out the WP Codex for more info on this
    http://codex.wordpress.org/Function_Reference/add_image_size

    When you’ve defined your image sizes you can refer to them by name in your template wherever you want to display them using get_the_post_thumbnail

    http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail

    1. Hey, thanks for the reply.

      I’m still not sure what you mean. I understand the method you outlined and it’s what I would normally do when there is only one featured image – my issue is how to change the size of the other featured images.

      So, using this code:

      if (class_exists(‘MultiPostThumbnails’)) {
      if (MultiPostThumbnails::has_post_thumbnail(‘folio’, ‘feature-image-2′)) {
      MultiPostThumbnails::the_post_thumbnail(‘folio’, ‘feature-image-2′);
      }
      }

      as you’ve instructed, where would I include either the array to change the size of the image, or the thumbnail size specified in functions? There’s no get_the_post_thumbnail here, so I don’t know where to include it.

      I hope you understand my problem, apologies but PHP isn’t my forte.

  10. Thanks for the feedback on this article. I’ll try to set some time aside to re-test the code and fix up the typos.

    I need to implement it again in a different site anyway so might as well try to fix up any bits and pieces at the same time.

  11. Thanks for this! I’ve used it similarly to the way you did(slider images), but adapted it for displaying a front page slider generated from the different posts that have a slider image in selected (I only added one additional featured image metabox). In order to select what position the featured image shows up, I added an extra custom field into the same image upload metabox that allows users to choose a position 1-6, then I plan to query the posts that have this custom field and order by the second custom field. I hope that made sense….anyway, thanks for the post! Helped me a lot.

  12. This is exactly what I need for my website. I do seem to have a problem though.

    Everything seems to work fine but when I click on “2nd Featured Image” (or any extra featured image) I can only set one featured image and it sets it to the “1st Featured Image”. I do not get the “Set as” options shown in your picture just above your “Displaying the post thumbnails in your WordPress posts” heading. I only have the default “Use as featured image”.

    Any help would be much appreciated. Thanks in advance!

  13. I should have really played around with the code further before posting that question. My problem was the following:

    I assumed that by setting the “post_type = ”” would mean that all post types would include the extra featured images. This did work when editing the post but when going to add a “2nd Featured Image” the option was not available as per my previous comment. I believe there is a bug in the multi-post-thumbnail plugin because when I comment out the code on line 123 to 126 of the PHP file, the options for extra thumbnails is there.

    This may be a bug or may not (I am not sure what the plugin writer’s intention was) but either way just be wary about this issue if you run into a similar problem as myself.

    Thanks for the great post Lars!

  14. Brilliant stuff. Bit confusing is this part:
    ‘post_type’ => ‘folio’
    … to test it in the first go make sure you use ‘post’ instead.

  15. How can i exclude this featured images??

    I try with this ID ) . ‘”]’); ?> but only exclude the main featured image.

    Thanks for your time.

    1. Sorry error posting the code

      How can i exclude from the native gallery I use the following code:

      ID ) . '"]'); ?>

      Thanks in advance for this hack, is really useful :)

  16. This is exactly what I was looking for to include in my themes for a page header image that can be specified for every page/post. The new meta-box and set image both display and function properly, however, the image is not outputing with the suggested code in the template files. I’ve tried by including this in my theme as per this tutorial and also with the plugin instead, neither is working. The plugin page has a few comments about this not working in WP 3.3.1, which is what I am running. Can anyone verify or dispute these claims and offer a solution?

    Here is what I am using to initiate in functions.php and call in my template:

    functions.php :
    add_image_size( 'Page Header', 936, 200, true );

    if (class_exists('MultiPostThumbnails')) {
    $types = array('post', 'page', 'tribe_events');
    foreach($types as $type) {
    $thumb = new MultiPostThumbnails(array(
    'label' => 'Page Header Image',
    'id' => 'page-header-image',
    'post_type' => $type
    )
    );
    }
    }

    page or post template :

  17. I’m not sure if anyone else was struggling to add their own custom image sizes but you just need to add your own declaration, i.e:

    this:

    MultiPostThumbnails::the_post_thumbnail('folio', 'feature-image-2')

    becomes:

    MultiPostThumbnails::the_post_thumbnail('folio', 'feature-image-2'), NULL, 'MY-IMAGE-SIZE-ID'

  18. Thanks a ton for this. Saved me the time of hand rolling this feature or hacking on multiple post thumbnails myself. One quick note, it’s much more “correct” in OO land to extend multiple post thumbnails than to mess with the code directly:

    require_once('lib/multiple-post-thumbnails/multi-post-thumbnails.php');

    /**
    * Extends MultiplePostThumbnails to work as a component of a theme rather than as a plugin.
    */
    class ThemeMultiPostThumbnails extends MultiPostThumbnails {
    public function enqueue_admin_scripts() {
    $template_url = get_bloginfo('template_url') . '/js/multi-post-thumbnails-admin.js';
    wp_enqueue_script("featured-image-custom", $template_url, array('jquery'));
    }
    }

    Now call this instead:

    new ThemeMultiPostThumbnails(...);

    Now your changes are encapsulated and you don’t have to worry about patching future releases or distributing a modified version of another author’s code. Yay Object Orientedness! :)

    1. Slight correction – the path should be:

      $template_url = get_bloginfo('template_url') . '/lib/multiple-post-thumbnails/js/multi-post-thumbnails-admin.js';

      Also I am in the habit of using “lib”, not “library” so adjust as needed to your example code. :)

  19. Hey I ran into an issue where when I click “Set as 2nd Feature Image” link it just links to “#” sending me to the top of the page but never adds the image (I don’t know if its a client side (JS) issue or server side (PHP) issue

    Any help would be greatly appreciated

    Thanks a lot

  20. Hi! I am new at this, and I am trying to implement this plugin/function to have more featured-images but I dont know where to put the codes you have show.
    In which line etc.

    Can someone please help me?

    THANKS!

  21. Is it possible to add a css class using the following?

    I have a thumbnail class ‘single-thumb’ I would like to have applied.

  22. Great tutorial.
    A couple of small errors, but nothing too challenging.

    public function enqueue_admin_scripts() {
    $template_url = get_bloginfo('template_url') . '/js/multi-post-thumbnails-admin.js';
    wp_enqueue_script("featured-image-custom", $template_url, array('jquery'));
    }

    and

    if (class_exists('MultiPostThumbnails') {
    if (MultiPostThumbnails::has_post_thumbnail('folio', 'feature-image-2')) {
    MultiPostThumbnails::the_post_thumbnail('folio', 'feature-image-2');
    }
    if (MultiPostThumbnails::has_post_thumbnail('folio', 'feature-image-3')) {
    MultiPostThumbnails::the_post_thumbnail('folio', 'feature-image-3');
    }
    if (MultiPostThumbnails::has_post_thumbnail('folio', 'feature-image-3')) {
    MultiPostThumbnails::the_post_thumbnail('folio', 'feature-image-3');
    }
    }

    Should be:

    if (class_exists('MultiPostThumbnails')) {
    if (MultiPostThumbnails::has_post_thumbnail('folio', 'feature-image-2')) {
    MultiPostThumbnails::the_post_thumbnail('folio', 'feature-image-2');
    }
    if (MultiPostThumbnails::has_post_thumbnail('folio', 'feature-image-3')) {
    MultiPostThumbnails::the_post_thumbnail('folio', 'feature-image-3');
    }
    if (MultiPostThumbnails::has_post_thumbnail('folio', 'feature-image-3')) {
    MultiPostThumbnails::the_post_thumbnail('folio', 'feature-image-3');
    }
    }
    Should be :

    public function enqueue_admin_scripts() {
    $template_url = get_bloginfo('template_url') . '/library/js/multi-post-thumbnails-admin.js';
    wp_enqueue_script("featured-image-custom", $template_url, array('jquery'));
    }

    Thanks again!

  23. Hi,

    I hahve a problem;

    everything is working except one thing… When I add an image to example “set 2nd feature image” It dosn’t show up in the meta box in the admin area.

    When I set the first feature image that’s in wordpress from the begining it works though.

    Everything else works, I can load it on my page and everything.

    Any help?

  24. yikes! When I add:

    // Load external file to add support for MultiPostThumbnails. Allows you to set more than one "feature image" per post.
    require_once('library/multi-post-thumbnails.php');

    Everything goes blank, version 3.4 of WordPress. Has anyone used this with the current version of WordPress?

  25. Since I upgraded WP to 3.4 ver, the plugin doesn’t even show up in plugin list. Does anyone have the same problem?

  26. Very useful technique. I used it for per page banners.
    Works well once I got the link right
    $template_url = get_bloginfo(‘template_url’) . ‘/library/js/multi-post-thumbnails-admin.js’;

    I will use this tip a lot & nicely integrated into the theme.

  27. if (class_exists(‘MultiPostThumbnails’)) {
    // Loops through each feature image and grabs thumbnail URL
    $i=1;
    while ($iID ); // use the MultiPostThumbnails to get the image ID
    $image_thumb_url = wp_get_attachment_image_src( $image_id,’small-thumb’); // define thumb src based on image ID
    $image_feature_url = wp_get_attachment_image_src( $image_id,’feature-image’ ); // define full size src based on image ID
    $attr = array(
    ‘class’ => “post-sample”, // set custom class
    ‘rel’ => $image_thumb_url[0], // sets the url for the image thumbnails size
    ‘src’ => $image_feature_url[0], // sets the url for the full image size
    );
    // Use wp_get_attachment_image instead of standard MultiPostThumbnails to be able to tweak attributes
    if ($i==2){
    $image = wp_get_attachment_image( $image_id, ‘your image size name which you declared in function.php’, false, $attr );
    echo $image;}
    if ($i==3) {
    $image = wp_get_attachment_image( $image_id, ‘your image size name which you declared in function.php’, false, $attr );
    echo $image;}
    if ($i==4) {
    $image = wp_get_attachment_image( $image_id, ‘your image size name which you declared in function.php’, false, $attr );
    echo $image;}
    if ($i==5) {
    $image = wp_get_attachment_image( $image_id, ‘your image size name which you declared in function.php’, false, $attr );
    echo $image;}
    }
    $i++;
    }
    };

  28. Thanks for this tutorial on multi-featured images. It’s exactly what I was looking for. I also noticed that you had integrated it into the Nivo Slider with thumbnail navigation, which is what I am currently trying to add to my theme’s templete.

    I tried using the slider code that you posted, but it didn’t yield any results. I was wondering how exactly you set up your Nico slider in terms of the coding used in the functions.php, the Nivo files you used, etc.

    I would very much appreciate any tips in this area.

    Thanks in advance!

  29. Is it possible for this to not include width & height attributes in the output? I’m building a responsive site & i need the images to be fluid

  30. AWESOME TUTORIAL also, thank you Stephen, probably never woulda figured that one out. I made a sweet slider with this using flexslider, works beautifully!

  31. Sorry to disturb, I got an issue.
    Because the plugin seems to attach the thumbnail to an article, if I want to use the “galery” feature , the thumbnail appears in this gallery.
    Do you know how I could avoid this ?
    Many thanks

  32. i want show more than one featured images i followed all the steps which is given above but it not showing of “Featured images” in admin i used the wordpress prime-theme for website

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>