WordPress Thumbnails Outside The Loop

Occasionally you’ll need to fetch a posts image outside of the loop.

<?php
    $thumb = get_post_meta($post->ID,'_thumbnail_id',false);
    $thumb = wp_get_attachment_image_src($thumb[0], false);
    $thumb = $thumb[0];?>
 
   <img src="<?php  echo $thumb; ?>" alt="" />

Combine this with the Timthumb script for control over image size. IE:

 
<?php
   $thumb = get_post_meta($post->ID,'_thumbnail_id',false);
   $thumb = wp_get_attachment_image_src($thumb[0], false);
   $thumb = $thumb[0];
  if ( has_post_thumbnail() ) { ?>
    <img src="<?php bloginfo('template_directory'); ?>/timthumb.php?src=<?php echo $thumb; ?>&amp;w=150&amp;h=150&amp;zc=1"
        alt="<?php the_title(); ?>" width="150" height="150" />
<?php } ?>

Not Recommended, But Available Option

This will output the URL to an image with the size predefined by ‘post-thumbnail’ in your functions file when registering the functionality for post images.

<?php
    $thumb = get_post_meta($post->ID,'_thumbnail_id',false);
    $thumb = wp_get_attachment_image_src($thumb[0], 'my-custom-size', false);
    $thumb = $thumb[0];
    echo $thumb; ?>

The above code is referencing ‘my-custom-size’, which we can see below as being 405×180. Typically it is not advised to use these predefined sizes as it will overload your uploads directory with additional sizes, and it puts strain on your server when uploading images. Better to use the above method with the Timthumb script to get an exact image size, while making use of image caching.

if ( function_exists( 'add_theme_support' ) ) { // Added in 2.9
	add_theme_support( 'post-thumbnails' );
	set_post_thumbnail_size( 50, 50, true ); // Normal post thumbnails
	add_image_size( 'my-custom-size', 405, 180, true );
}

7 Comments
  1. 网络推广 June 29, 201012:42 am

    你好,不错啊!

  2. John Roescher July 22, 20107:46 pm

    Very helpful, thanks!

  3. 导航 August 1, 20105:54 am

    这篇不错

  4. 淘宝店铺介绍 August 4, 20109:53 pm

    博客写的不错!!
    咱的小站:http://www.webshop1688.com

  5. replica breitling watches October 6, 20103:11 am

    Thanks for your visiting this http://www.glamour-watch.com/replica-pen online store,It is a good idea for getting your desired Imitation Watches or Replica Rolex Paypal. we are a professional,loyal and reliable store for your need Replica Watches Paypal.

Submit Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

To include your code, use pastebin, and paste the URL in the comment body. Failure to do so may prevent your comment from appearing. Thank you.