Advertisement
Theme Development

Automagic Post Thumbnails & Image Management

by

Using a custom post thumbnail or featured image function for your posts and pages in WordPress has been a well known trick for a while now. You can use it to create content sliders or other related functions which enhance the overall look of a WordPress site... but using such features can sometimes give you some trouble (or at least I have experienced some difficulties), especially when I'm updating my blog from my mobile device using WordPress for Android or WordPress for BlackBerry. Today, I'm going to show you a few tricks that have helped me out in the past - hopefully they'll help you out as well!

In this article, I will share with you how to detect the first image in your post attachments or use a default thumbnail defined for your theme development. You can view the example of this function on my Personal Blog. You can use this snippet in your theme for easy thumbnail management and give user a better user experience using your theme.


WordPress Post Thumbnails

Before we get started, it's worth noting that I won't be using the official "post thumbnails" feature in this particular tutorial. Obviously, this is the gold standard preferred way to grab a post "featured image"... but there are a few technical reasons for why you might not want to use that:

  • The theme already uses the_post_thumbnail(); function for something else. For instance: You want to grab an image for a custom slider, but the official post-thumbnail is already being used for an actual thumbnail (and you don't want to worry about odd cropping if you use one image for both instances).
  • You don't like the code output of the_post_thumbnail();. I won't go too far into this, but for really custom situations it can actually be easier just to grab an image this way than to wrestle with getting the_post_thumbnail(); to output the way you'd like.
  • You want lots of different "post-thumbnails" at radically different sizes and ratios... and you aren't satisfied with how WordPress is cropping them using the_post_thumbnail();.
  • Your post images are hosted elsewhere. Meaning, you can't grab them using the_post_thumbnail() because they aren't actually hosted on your server.
  • You simply want to try something new. We'll be going over some techniques here that are just plain interesting whether you have an immediate use for them or not!

There might be more reasons that you can come up with, but these were the main reasons that I ended up using the method that I'll be going over here. Keep in mind that I'm not disregarding the_post_thumbnail(); There's a whole lot that you can do with that alone, and we'll probably be providing an in-depth tutorial on the subject in the next week or two just to supplement this!


Step 1 Grabbing the Custom Field

First of all, we will use a custom field to define our thumbnail. You can read more about setting this up using a "custom meta box"... but let's just assume that you have a custom field already set up (you can enter it manually if you don't want to bother with a custom meta box ). for this tutorial, I'm using the custom field "wpt_image" for the thumbnail. Outside of using the_post_thumbnail(); This is the simplest way for us to define custom thumbnail for our post.

	$related_thumbnail =  get_post_meta($post->ID, 'wpt_image', $single = true);

Step 2 Grabbing Image Attachments In The Post

Next we will check if the custom field is empty or not. If the custom field for image is empty, we will try to fetch any image attachment from the post. You can simply use the Upload/Insert function and upload a new image without the need to actually insert it into the article. WordPress will assign the attachment to the post ID automatically.

The code below will try to fetch the first attachment available in the post.

$attachments = get_children( array(
	'post_parent'    => get_the_ID(),
	'post_type'      => 'attachment',
	'numberposts'    => 1, 
	'post_status'    => 'inherit',
	'post_mime_type' => 'image',
	'order'          => 'ASC',
	'orderby'        => 'menu_order ASC'
) );

If at least one attachment is found, then we will read the attachment url.

if(!empty($attachments)):		//check if there an attachment or not
	foreach ( $attachments as $attachment_id => $attachment ) {
		  if(wp_get_attachment_image($attachment_id) != ""):
			  $related_thumbnail = wp_get_attachment_url( $attachment_id );
		  endif;						
	}

We will use the first image attachment url as our default thumbnail url.


Step 3 Detect Any Image Found in a Post

What if there are no attachment or custom field value found? We will try to fetch any image in the article that was inserted without using the upload function. This is useful when we use an image from media library, because the attachment id will be assign to other post.

$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('//i', $post->post_content, $matches);
$first_img = $matches [1] [0];

Step 4 Define A Default Thumbnail As a Fallback

What if all the conditions above return no value? Well, you can opt to not use any images at all, or, you can define a "default" image placeholder. We will define our own default thumbnail to be use. This is where I find it very useful, especially when I'm updating my blog from mobile apps. I don't need to define any custom field or upload an image, I can simply write my article and upload it to my blog, and the function will do all the magic to ensure my front page look as good as I want it to.

$related_thumbnail = "images/default_thumbnail.jpg";	//define default thumbnail, you can use full url here.

Upload your "default_thumbnail" image to your theme directory, or you can use a full url instead.


Usage: How to Use This Function

To use this function, put the whole function in your theme functions.php file, then you can use the function like example given below

	

or, if you want to use this function together with an image resizer such as TimThumb or WordThumb, upload the required files from timthumb/wordthumb to your theme directory and use the following code instead

	

Putting it All Together: Full Source Code

For anyone who is having some trouble putting it all together. Here is the full source code (download from link at the top), ready to just paste into the functions.php file:


ID, 'image', $single = true);							//read post meta for image url

	if($related_thumbnail == ""):
		$attachments = get_children( array(
									'post_parent'    => get_the_ID(),
									'post_type'      => 'attachment',
									'numberposts'    => 1, 
									'post_status'    => 'inherit',
									'post_mime_type' => 'image',
									'order'          => 'ASC',
									'orderby'        => 'menu_order ASC'
									) );
		if(!empty($attachments)):												//check if there an attachment or not
			foreach ( $attachments as $attachment_id => $attachment ) {
			  if(wp_get_attachment_image($attachment_id) != ""):
				  $related_thumbnail = wp_get_attachment_url( $attachment_id );
			  endif;						
			}
		else:															// if no attachment 
			$first_img = '';
			ob_start();
			ob_end_clean();
			$output = preg_match_all('//i', $post->post_content, $matches);
			$first_img = $matches [1] [0];
			
			if(!empty($first_img)):
				$related_thumbnail = $first_img;
			else:
				$related_thumbnail = "images/default_thumbnail.jpg";							//define default thumbnail, you can use full url here.
			endif;
		endif;	 
	endif;	
	
	echo $related_thumbnail;
}

Conclusion

By now you should be able to use this function in any of your themes in supplement to (or instead of) using the_post_thumbnail(). If you have any additional suggestions or questions regarding custom images, feel free to leave a comment!

Related Posts
  • Code
    Tips
    New wp-config Tweaks You Probably Don't Know8 new wp config tweaks you probably didnt know about 400
    The wp-config.php file: One of the most loved WordPress feature for some, one of the worst nightmares for others. There are countless tips and tricks in a plethora of articles, and you can't get enough of them; however, this article is aiming to be different. In this article, we're going to get familiar with eight new wp-config tricks that are less known than functionality such as turning off post revisions, increasing the memory limit, or other similar features.Read More…
  • Code
    Creative Coding
    Advanced Use of Attachments in WordPress: Creating Custom Queries for AttachmentsAdvanced use of attachments in wordpress 400
    This tutorial is the second in a four part series in which you'll learn some techniques for working with images in attachments in WordPress which give you advanced options.Read More…
  • Code
    Theme Development
    Creating a WordPress Theme From Static HTML: Releasing Your ThemeCreating wordpress theme from html 400
    If you've been following this series you now have a working WordPress theme. Your theme has a number of template files, including a page template and an archive template, and also has featured image support.Read More…
  • Code
    Theme Development
    Creating a WordPress Theme from Static HTML: Adding Featured ImagesCreating wordpress theme from html 400
    You've now worked through a number of steps to create a WordPress theme from static HTML files. Specifically, we've looked covered the following: preparing your markup for WordPress converting your HTML to PHP and splitting your file into template files editing the stylesheet and uploading your theme to WordPress adding a loop to your index file adding meta tags, the wp_head hook and the site title and description to your header file adding a navigation menu adding widget areas to the header and sidebar adding widget areas, a colophon and the wp_footer hook to the footer file creating template files for static pages creating an archive template file. Your theme now has a template file for displaying archive pages, but at the moment it's not displaying images properly. In this tutorial, you'll learn how to add featured image support to your theme and how to display and style them in your archive template.Read More…
  • Code
    Plugins
    Create a Shortcode to List Posts With Multiple ParametersPost listing shortcode main image400
    On many of the client sites I build, I find there are times when I need to include a post listing on a page. I'm not talking about archive pages here, but adding a custom listing to an existing static page. For example, I might want to list some posts on the 'About' page, or the site may require an in-depth page for a topic, with a list of posts and custom post types related to that topic. One way to do this is by creating a custom page template to include the current page content plus the results of a second custom query, but if you want more flexibility over how you list posts, or just want to do it a few times, a shortcode will be a simpler solution. In this tutorial, I'll show you how to create a simple shortcode to list all posts of a custom post type, and then I'll expand on that to create a shortcode with various parameters that users can specify to list posts however they want.Read More…
  • Code
    Plugins
    How to Create a WordPress Avatar Management Plugin from Scratch: Finishing TouchesPreview
    Avatar Manager for WordPress is a sweet and simple plugin for storing avatars locally and more. Easily. Enhance your WordPress website by letting your users choose between using Gravatar or a self-hosted avatar image right from their profile screen. Improved workflow, on-demand image generation and custom user permissions under a native interface. Say hello to the Avatar Manager plugin.Read More…