WordPress – Get thumbnails for your images with custom sizes

by KishPress on July 23, 2011

If you want to display thumbnails along with the post excerpts then you can use the WordPress built in image crop function rather than going for something like phpThumb which is something good, but your server resources should support.

function get_the_thumb($width, $height, $cut = true){
	if(is_null($height)) $height = $width;

    // read the content
    $content = apply_filters('the_content', get_the_content());
    // extracct the first image
    $img = extract_image($content);
	if(strlen($img)) {
		if(strpos($img, 'kish.in')===false) {
	     	return "http://img.xxxx.ixxxxn/index.php?url={$img}&w={$width}&h={$height}";
		}
		else {
			return generate_thumb($img, $width, $height, $cut);
		}
	}
	else {
		return "";
	}
    // return the thumb

}

function generate_thumb($img_url, $width, $height, $cut = true){
    // cut the url
    require_once(ABSPATH . '/wp-admin/includes/image.php');
    if(strpos($img_url, 'wp-content')===false) {
    	$img = str_replace("http://images.kish.in", "", $img_url );
    	$img='images'.$img;
    	$prefix="http://images.kish.in";
    }
    else {
    	$img = substr($img_url, strpos($img_url, 'wp-content'));
    	$prefix=get_bloginfo('wpurl');
    }
    // resize the image
  	$thumb = image_resize($img,$width,$height,$cut);
  	if(is_string($thumb)) {
	  	if($prefix=="http://images.kish.in") {
	  		$thumb=str_replace("images/", "", $thumb);
	  	}
	  	//echo $thumb;
	    return $prefix . '/' .  $thumb;
  	}
  	else {
  		return "";
  	}
}

/*
 * Extract the first image src inside some html content
 *
 * @param html $content
 */
function extract_image($content){
    $pattern = '~<img />~';
    preg_match($pattern, $content, $match);
    return $match[1];
}

One problem is that you can only use images that are stored on your server. I use a sub domain to store all the images, so I am checking for that. External images are taken care by a different script which uses phpThumb.

Related posts:

  1. How to extract YouTube Thumb Image URL from a YouTube Video URL using PHP Script If you have thumbnails for your blog theme and you...
  2. Updating post custom fields using XMLRPC – WordPress Updating the custom data of a post which can be...
  3. All in One Seo Plugin and Twenty Ten Theme : Issue with Title when Re-Write Title Enabled After upgrading to WordPress 3.0, I changed my theme to...
  4. Enabling Remote Publishing in WordPress For communicating with a blog using the XMLRPC protocol, the...
  5. WordPress Comment Moderation Tool (WordPress Plugin) There are many blog owners who get tons of comments...

Leave a Comment

Previous post:

Next post: