Using WordPress’ the_post_thumbnail with Lightbox

by admin on September 26, 2010 · 9 comments

Using the_post_thumbnail with Lightbox

Note: This is not a Thesis tutorial. When Thesis launched, WordPress didn’t have post images, so Thesis had its own method of using them and it was great. Now that WordPress has native support for them, I prefer to use that. To learn how to use the_post_thumbnail with Thesis, check out this article or this article.

WordPress 2.9 brought us the_post_thumbnail, which lets us set a photo for a post without using custom fields. It works really well and it’s one of my favourite newer features. The post thumbnail works with WordPress cropping functions and can be called at various sizes. Now, wouldn’t it be cool to show just a thumbnail, and then have a bigger photo open in a Lightbox script when clicked?

I thought it would be, and figured it would be easy, but there was one problem:

Most Lightbox scripts work by placing a link to your full-sized image and adding rel=”lightbox” to it. When you call the_post_thumbnail, WordPress doesn’t just spit out the URL, but also a whole lot of other code. We need to get rid of that first, and then rock and roll.

Here’s a quick tutorial on using the post_thumbnail with Lightbox:

  1. Add post_thumbnail support

    Add the following to your theme’s functions.php file, if it’s not already there:

    <?php add_theme_support( 'post-thumbnails' ); ?>

    Now when you go to a post page, you’ll see an option on the bottom of the right hand side that allows you to set a post thumbnail. Easy enough. Let’s move onwards.

  2. Install Lightbox

    There are lots of lightbox scripts out there, and this isn’t a tutorial on how to work them. I like to work with Slimbox because it’s tiny and uses jQuery, but the original Lightbox script is the most popular. Whichever script you choose, install it according to its instructions.

  3. Add your post_thumbnail

    Now here comes the tricky part. In your single.php or wherever you want to place the image, put:

    preg_match ('/src="(.*)" class/',$thumbnail_id,$link);
    echo $link[1];
    <a href="<?php echo $link[1]; ?>" rel="lightbox"><?php the_post_thumbnail('thumbnail'); ?></a>

    This strips out all the extra HTML and gives us just the link, allowing us to append rel=”lightbox” to it. Awesome. You can change “thumbnail” to whatever size you want the thumbnail to be.

And that’s it. Lightboxy goodness.

Get the_post_thumbnail direct path for WordPress

Further reading on post_thumbnails:
Function Reference/the post thumbnail
Everything you need to know about WordPress 2.9′s post image feature
The Ultimate Guide For the_post_thumbnail in WordPress 2.9
New in WordPress 2.9: Post Thumbnail Images