LATEST BLOG ENTRY

Timthumb and Shortcodes for Easy Wordpress Images

August 12, 2010 • 1 Comments

Here’s a quick and easy way to update image sizes on the fly directly in your Wordpress posts. Add this code into your functions.php file in your theme. Then make sure you insert timthumb.php in the root of your theme directory. Next create a fully writable directory named ‘cache’ and place that in your theme root directory.

Now inside your posts just wrap an image URL with the img shortcode. Add height, width, alt, and class to it for more flexibility.

1
2
3
4
5
6
7
8
9
10
11
12
// Image resize in content  
// To Use: [img w=600 h=200 class=alignleft alt=My Photo]http://mysite.com/photo.jpg[/img]
function timmyimg($atts, $content = null) {
	extract(shortcode_atts(array(
		'w' => '600',
		'h' => '250',
		'class' => 'alignnone',
		'alt' => ''
	), $atts));
	return "<img src='". get_bloginfo('template_directory') . "/timthumb.php?src=".$content."&w=".$w."&h=".$h."' alt=".$alt." class='wp-post-img ".$class."' />";
}
add_shortcode('img', 'timmyimg');
Forrest


Forrest Forrest

Wordpress Thumbnails Outside The Loop

June 23, 2010 • 6 Comments

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

1
2
3
4
5
6
<?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.

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.

1
2
3
4
5
<?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.

1
2
3
4
5
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 );
}

PREVIOUS ENTRIES

The Mercy of God

January 4, 2010