Catch the First Image (Upgraded)
Brian asked me here about Catch the First image function can be upgrade. I was coded this function for my Turkish blog for Home Page thumbs. If you set no image about post (not the wordpress post thumb feature, if you dont upload any image) this function get custom (default) image for this. Let’s Begin…
The Code;
You will edit your theme’s functions.php. Because of this you should backup before. File’s path is /wp-content/themes/your-theme/functions.php
// Get Image Attachments
function sa_get_image($postid=0, $size='thumbnail') { //it can be thumbnail or full
if ($postid<1)
$postid = get_the_ID();
$thumb = get_post_meta($postid, "thumb", TRUE); // Declare the custom field for the image
if ($thumb != null or $thumb != '') {
echo $thumb;
}
elseif ($images = get_children(array( //If you upload an image function gets first image
'post_parent' => $postid,
'post_type' => 'attachment',
'numberposts' => '1',
'orderby' => 'menu_order',
'order' => 'ASC', //If reverse use DESC
'post_mime_type' => 'image', )))
foreach($images as $image) {
$thumbnail=wp_get_attachment_image_src($image->ID, $size);
?>
<?php echo $thumbnail[0]; ?>
<?php }
else { //If you don't upload or declare as thumb custom field func. gets custom (default) image
echo get_bloginfo ( 'template_directory' ); //same as wp-content/themes/your-theme/
echo '/images/image-pending.gif'; // Put this image into your themes images folder and set the path here
}
}
You can use this function with your several files like index.php, single.php or anything.
<img src="<?php sa_get_image($post->ID, 'thumbnail'); ?>" />
If you set your thumbnail size 100*100 from wordpress you can get a thumbnail image where you want. Also you can use another function with that. You can style your image’s div or you can use timthumb.
Without Timthumb;
// Show Post Thumbnails
function sa_show_thumb_tim() {
?>
<a href="<?php the_permalink() ?>" rel="bookmark"><img class="thumb" width="100" height"100" src="<?php sa_get_image($post->ID, 'full'); ?>" alt="<?php the_title(); ?>" /></a>
<?php
}
You can use this like this directly. Because we coded function with img tag.
<?php sa_show_thumb(); ?>
With Timthumb;
// Show Post Thumbnails With TimThumb
function sa_show_thumb_tim() {
?>
<a href="<?php the_permalink() ?>" rel="bookmark"><img class="thumb" src="<?php bloginfo('template_directory'); ?>/timthumb.php?src=<?php sa_get_image($post->ID, 'full'); ?>&h=100&w=100&zc=1" alt="<?php the_title(); ?>" /></a>
<?php
}
You can use this like this directly. Because we coded function with img tag and we add timthumb function. You can get the latest version of timhtumb here. And you have to put timthumb.php into your theme’s folder.
<?php sa_show_thumb_tim(); ?>
Best Regards
