Most of the themes available for WordPress nowadays uses the much popular TimThumb script which can resize images on the fly. The script actually needs an image from the post and then resizes them according to the size you have specified. But for fetching the image, most of the themes uses custom fields and specifying the custom field for getting an image from the post. When publishing post, you need to specify a custom field and then add the image URL as the value. But with a simple php function, you can easily fetch the first image from any post, here is how to get it.
Open the functions.php file in your WordPress theme currently being used. At the end of the functions, add the below script.
// Get URL of first image in a post
function get_first_image()
{
global $post, $posts; $first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
// no image found display default image instead
if(empty($first_img))
{
$first_img = "https://cdn.nirmaltv.com/images/default.jpg";
}
return $first_img;
}
Now save the file and call the function <?php echo get_first_image() ?> in your template file within the loop. So for each post, it gets the first image and this value can be passed to TimThumb script for resizing images on the fly.
This function makes it easy to use the resize script without having to use any custom fields or settings.
Thanks to WordPress forums for this tip.