Ultimate method to add post thumbanils to your wordpress theme

Wordpress Hacks
Wordpress Hacks

In this tutorial, I will show you the best method to add post thumbnail feature to your wordpress theme. This is what we are going to do.

  1. We will check if there is any image set in custom fields, if yes we display that image.
  2. Else we check if there is any image stored in the gallery associated with that post, if found we display that image.
  3. Else we do a pattern match for image url’s over the post content and extract the images used in the post, with this method we will be able to pull out images that are not part of wordpress gallery.

How to create a custom field?

To do this, simply start making a New Post, and scroll down the page until you see “Advanced Options“.  Under this heading, you should see something like, Excerpt, Trackback, and Custom Fields.

Adding post thumbnails using wordpress custom fields
Adding post thumbnails using wordpress custom fields

To add a Custom Field for a Thumbnail, just fill in the Key with “image”.  For the Value, post the full URL of the thumbnail you would like to use.

Click Add Custom Field, and it will apply to that post.

Adding thumbnail to our post

Add the following code before
the_content() / excerpt()

[php]
<?php
//Getting the image url from custom field
$img = get_post_meta($post->;ID, ‘image’, $single = true);
/*If the custom field url is empty, then we look for
images stored in galler associated with the post. If
there are no images associated with the gallery we
proceed further and do a pattern matching to identify
images in the post content.
*/
if(!$img){
//Get images attached to the post
$args = array(
‘post_type’ => ‘attachment’,
‘post_mime_type’ => ‘image’,
‘numberposts’ => -1,
‘order’ => ‘ASC’,
‘post_status’ => null,
‘post_parent’ => $post->ID);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment)
$img = wp_get_attachment_thumb_url( $attachment->ID );
}
else{
//Extracting the content of the post to do a pattern match
$content = $post->post_content;
//A simple regular expression to identify image urls.
$searchimages = ‘~http://[^>]*.(jpg|jpeg|gif|png)~’;
preg_match( $searchimages, $content, $pics );
$iNumberOfPics = count($pics[0]);
if ( $iNumberOfPics > 0 )
$img=$pics[0];
}
}
/*If we get a image url in any of the above steps, we echo the
following code to display the image. set the height or width
attribute so that image doesn’t break the layout and doesnt look
distorted.
*/
if($img){?><img src="<?php echo $img;$img=NULL; ?>"   height="150"/><?php }
?>
[/php]

2 Replies to “Ultimate method to add post thumbanils to your wordpress theme”

  1. Pingback: Tweets that mention Ultimate method to add post thumbanil to your wordpress theme. | Swift Themes -- Topsy.com

Comments are closed.