Controlling Post Thumbnails with PHP

Wednesday April 14th, 2010

With the release of WordPress 2.9 along came the sweet new functionality to specify a thumbnail for each post in your blog. The basic approach to this feature is described in great detail here, here and here but what these articles don’t describe is how to get access to a specific post thumbnail through any means other than the the_post_thumbnail() function. Today I am going to show you how to do just that.

This issue first arose for me when I was developing the carousel on my site’s homepage. I wanted to get a list of posts and then store their titles, excerpts and thumbnails inside of arrays that could be passed to Javascript for use in the carousel. Getting the titles and excerpts was easy enough:

<?php
        $images = array();
	$titles = array();
	$descriptions = array();

	$index = 0;

	$portfolio_posts = get_posts(array('category_name' => 'Portfolio'));

	foreach ($portfolio_posts as $portfolio_item)
	{
		$titles[$index] = $portfolio_item->post_title;
		$descriptions[$index] = $portfolio_item->post_excerpt;

		$index++;
	}
?>

But I was unable to figure out how to access the thumbnails. After some digging I came across post-thumbnail-template.php in /wp-includes and discovered that using this:

<?php
        $thumb_id = get_post_thumbnail_id($portfolio_item->ID);
        $thumb = wp_get_attachment_image_src( $thumb_id, 'portfolio-large', false);
?>

will return the location of the image you set as the thumbnail at the specified size as well. It may seem simple but the benefit of this is that you can set and change the thumbnail image you want to use inside of WordPress and the template will automatically update it. No messing around with image ID’s and no hardcoded values.

Here it is all together:

<?php
	$images = array();
	$titles = array();
	$descriptions = array();

	$index = 0;

	$portfolio_posts = get_posts(array('category_name' => 'Portfolio'));

	foreach ($portfolio_posts as $portfolio_item)
	{
		$thumb_id = get_post_thumbnail_id($portfolio_item->ID);
		$thumb = wp_get_attachment_image_src( $thumb_id, 'portfolio-large', false);

		$images[$index] = $thumb[0];
		$titles[$index] = $portfolio_item->post_title;
		$descriptions[$index] = $portfolio_item->post_excerpt;

		$index++;
	}
?>
Sharing is Caring
  • Reddit
  • Digg
  • Facebook
  • Twitter
  • del.icio.us
  • StumbleUpon

Comments

Controlling Post Thumbnails with PHP has 1 comment so far.

Leave a comment




* Denotes required fields. But you knew that.