Getting Post thumbnail on WordPress 3 w/ w/o specific Post ID

Previously we have discussed about how to activate and set custom post featured image sizes using two WordPress APIs, add_theme_support and add_image_size. After this, the tutorial on how to actually use the generated thumbnails, was really pending. And I am really sorry that I could not bring this tutorial the day after I published the previous tutorial. I really became busy with the WordPress Plugin and my collage’s website development.

But, anyways, its never too late.. So today we will discuss how we can use WordPress’ another two API’s the_post_thumbnail and get_the_post_thumbnail.

#1: Using the_post_thumbnail:

The primary API to get and display the post thumbnail. So, this will echo the IMG HTML with the SRC to the post thumbnails… Here are its specifications:

#1.1: Parameters:

It accepts two parameters, size and attribute.

  • $size: (mixed) The size of the featured thumbnail to display. It can be a string or an array with height, width.
  • $attr: (array) The sets of attributes. It accepts the following parameters. Given are their default values:
    $default_attr = array(
        'src'	=> $src,
        'class'	=> "attachment-$size",
        'alt'	=> trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
        'title'	=> trim(strip_tags( $attachment->post_title )),
    );
    

#1.2: Usage Notes:

The usage is restricted in a way that, it should be used within the Loop. So, you can not pass post id to get and display specific thumbnails or featured images. If that is the case, then use get_the_post_thumbnail.

#1.3: Basic usage and Example:

Below is the basic syntax guide.

/**
 * Getting post thumbnail with predefined size (custom-thumbnail)
 * and Custom sets of attr
 */
$my_thumb_attr = array(
    'class' => 'my-class',
    'title' => 'Go to the post'
);
the_post_thumbnail('custom-thumbnail', $my_thumb_attr);

/**
 * Basic usage with custom size
 */
the_post_thumbnail(array(100, 100));

This is the complete example…

#1.3.1: Our theme’s functions.php file:

Here we add the thumb support and make a custom size of 256X256.

/**
 * Enable the post thumbnail support
 * Add the custom 150X150 image size
 */
if(function_exists('add_theme_support')) {
    /** Register the post thumbnail */
    add_theme_support('post-thumbnails');

    /** Register custom size */
    add_image_size('itg-ex', 100, 100, true);
}

#1.3.2: The index.php file:

Here we show the post excerpt with our custom thumbnail.

<?php
/**
 * Loop through the posts
 * Use the excerpt and our custom thumbnail size
 */
if(have_posts()) : while(have_posts()) : the_post();
?>
<div class="post-content">
    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <div class="content">
        <?php
        /**
         * Check to see if post has thumbnail
         */
        if(has_post_thumbnail()) {
            ?>
            <div class="my_thumb">
                <?php the_post_thumbnail('itg-ex', array('class' => 'alignright')); ?>
            </div>
            <?php the_excerpt(); ?>
            <?php
        }
        ?>
    </div>
</div>
<?php
endwhile; endif;
?>

#2: Using get_the_post_thumbnail:

This is a bit advanced than the_post_thumbnail. It allows you to pass through the post id to get the thumbnail. Note that this will return the IMG HTML instead of echo-ing it.

#2.1: Available parameters:

In addition to the previous two parameters, it gives another parameter $id, to pass the post ID.

  • $id: (integer) This is a Required parameter. It gets the thumbnail from the given post id.
  • $size and $attr: Same as the_post_thumbnail.

#2.2: Usage Note:

This API does not automatically get the post thumbnail, when used inside the loop. You are required to pass in the id parameter no matter where you use it.

#2.3: Usage example:

This depends upon your necessity. For displaying inside the main Loop, you can use the_post_thumbnail, but in case you are using get_posts then you can use get_the_post_thumbnail to get and store the featured image html. For example, I am using the following peace of code for my new widget plugin. (It’s RC now! You can safely install. The next post will be about the plugin’s final release 😉 )

<?php
/**
 * Get the posts by a category
 */
$my_posts = get_posts(array('cat' => 2));
/**
 * Initiate the output
 */
$output = '';
/** Loop through the post */
foreach($my_posts as $post) {

    /** Add Thumbnail to the anchor if present
     * Else The post title
     */
    $output .= '<li><a href="' . get_permalink($post->ID) . '">';
    if(has_post_thumbnail($post->ID))
        $output .= get_the_post_thumbnail($post->ID);
    else
        $output .= $post->post_title;

    /**
     * Close the widget
     */
    $output .= '</a></li>';
}
echo $output;
?>

Also, here are some basic implementation:

get_the_post_thumbnail($id);                  // without parameter -> Thumbnail

get_the_post_thumbnail($id, 'thumbnail');     // Thumbnail
get_the_post_thumbnail($id, 'medium');        // Medium resolution
get_the_post_thumbnail($id, 'large');         // Large resolution

get_the_post_thumbnail($id, array(100,100) ); // Other resolutions

#3: Notes and Tips:

  • While using any of the API, your theme or plugin need to have the post-thumbnails enabled. You should read this post to get detailed information about how to enable them and how to add different image sizes.
  • You can use has_post_thumbnail to check if the post has featured image set or not.
  • Calling any of the API without add_theme_support( ‘post-thumbnails’) will give Fatal Error of calling undefined function.
  • For previous posts, whose featured image were set before registering a custom size, will give HTML sized (maintaining aspect ratio) images, no matter you have enabled cropping via the add_image_size or not. Viper007’s regenerate thumbnail can be used in such case. Although I have not tested it, but I have a feeling that it will work :).

External Resources:

And that is all! Hope, you have enjoyed the article. Do give us your feedback and if you face any trouble, feel free to ask.

13 comments

  1. Free Logo Design

    Good news, I think. A great looking comments section encourages readers to comment, I believe.And of course I don’t code, so this doesn’t really add too much work for me .

  2. Pingback: Set Wordpress Post Thumbnail with custom size & cropping | InTechgrity

  3. Tobi

    nice one!
    i’m wondering if there’s another way besides scaling or croping the thumbnail from the original image.

    or lets say.. is there a way to define the croping area of the big image for the thumbnail?

    now, when croping, wordpress takes everything from the top left corner of the original image – which sometimes is just the wrong part of the image.

    so i’m looking for a way to give the backend user the ability to choose which port of the big image should be the thumbnail.. do you have any idea how to do that?

    by now i’m going to give him the possibility to upload a second (thumbnail) picture which (if it exists) will override the generated thumbnail.

    tobi.

  4. Free Logo Design

    i’m looking for a way to give the backend user the ability to choose which port of the big image should be the thumbnail.. do you have any idea how to do that?

  5. Josh

    Thank you for the tips. I tried to pass 3 arrays into the the_post_thumbnail() but the last one doesn’t work for me.

    the_post_thumbnail(
    array(width,height),
    array(“class” => “alignleft ” . ” featured_image”),
    array(“title”=> “Title”)
    );
    It doesn’t get the last array parameter, Is there a way to include 3 arrays in the_post_thumbnail()? Thanks in advance!

  6. Sam Fourie

    Let this be known!!

    Your description on this here “Post Featured image” is the only one of many, many I tried that actually works !

    Well done, and many thanks
    Sam Fourie

  7. Kegan Quimby

    I’m trying to have the featured image not show on the post page (so users can ‘insert an image’ into the post, without having to be stuck with the styling of the featured image), I’m just wondering what is the best way to go about this? Create a widget? Add custom CSS to EVERY page? that seems redundant…

    great article, btw.

    • Jack

      You just need to edit your theme’s single.php to remove the code that displays the featured image. It will look something like this:
      'alignright')); ?>

      • Jack

        That code didn’t display quite right. It will include: the_post_thumbnail

  8. Pingback: WordPress Multisite (WP-MS) compatibility for TimThumb | InTechgrity

  9. Pingback: Get the souce URL (src) of the full sized featured image in WordPress

Comments are closed.