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.
- We will check if there is any image set in custom fields, if yes we display that image.
- Else we check if there is any image stored in the gallery associated with that post, if found we display that image.
- 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.
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]
Nice Tutorial, Satish.
But a more simpler method is to use the first image of every post as the post thumbnail.
http://inforids.com/best-simplest-way-to-add-thumbnail-to-post-excerpts-in-wordpress-themes/