WordPress Post Thumbnails – Just another Solution

Nov 19th, 2009 6 Comments

Ok since we all know that 1 image = 1000 words, I will share with you how to you easily have post thumbnails with nothing more than what wordpress offers. This piece of code will get the first uploaded image or the first inserted image and create a thumbnail for you with a link to that post, and you can specify a nice image for posts that have no images and put that image in your theme /images folder and name the image thumb_noimage.jpg

Add this code where you want the thumbnails to appear

<?php print_post_thumb($post) ?>

Add this code to functions.php

// Gets the first uploaded image AND/OR first inserted image into post 
function get_thumb_first_post_image($post,&$thumb_url) {
	//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) {
       	$thumb_url = wp_get_attachment_thumb_url( $attachment->ID );
                return 1;
		 }
	}
}
// This Prints an image when there is no img in the post 
//Note:you can change the path to your images folder
function get_thumb_no_image($post,&$thumb_url) {
	$content = $post->post_content;
	$thumb_url = get_template_directory_uri() . '/images/thumb_noimage.jpg';
	return 1;
}
// Generates the image with link to the post 
//Note:Change the width and height to your needs
function get_post_thumb($url,$title,$img) {
	return '<a href="' . $url . '" title="' . $title . '"><img src="' .
		$img . '" alt="' . $title . '" width="150px" height="150px" /></a>';
}
// Prints the generated images into theme
function print_post_thumb($post) {
		get_thumb_first_post_image($post,$thumb_url)
	 ||	get_thumb_no_image($post,$thumb_url);
	echo get_post_thumb(get_permalink($post->ID), $post->post_title,
					$thumb_url);
}

5 Responses to “WordPress Post Thumbnails – Just another Solution”

  1. پدال says:

    thanks. very nice article…keep on the good work

  2. toby says:

    Thank you for sharing your free premium templates located at http://wparchive.com/wptube-video-wordpress-theme/..

    Great design..

  3. mojacho says:

    Hey brother, i still cant find your template @ themeforest.com..

    is there anyway for me to get it ???

    Thanks

  4. Suat says:

    Përshëndetje… nëse m’lejohet në shqip.

    A mund të na tregosh kodin për video post.
    Në një artikull kam postuar një video embed nga youtube dhe në index kam dëshir të shfaqet vetëm një thumb nga i nxjerur automatikisht nga klipi i youtubes, ndërsa kur të hy brenda artikullit të shfaqet video klipi pa thumb-in ?

orjin krem complex 41 ozoderm balderesi bioser galatasaray fenerbahçe canlı izle