How to get images from posts (and videos)


Post thumbs on your home page or category archives look very snazzy.

Here is a function you can put into your theme functions.php and call it in your index or archive templates, to show the thumbnail image extracted from the post.

This is a quick and simple hack. The function will just get the url of the image, or in case you use Smart Youtube plugin the representing image of the video. That means you still need to resize it with CSS or create and save thumbnail. WordPress 2.9 will include a function for this but it won't retrieve youtube thumbnails.

function get_image($text)
{
 
$imageurl="";
preg_match('/<\s*img [^\>]*src\s*=\s*[\""\']?([^\""\'>]*)/i' ,  $text, $matches);
$imageurl=$matches[1];
 
if (!$imageurl)
{
 preg_match("/([a-zA-Z0-9\-\_]+\.|)youtube\.com\/watch(\?v\=|\/v\/)([a-zA-Z0-9\-\_]{11})([^<\s]*)/", $text, $matches2);
 $youtubeurl = $matches2[0];
 if ($youtubeurl)
    $imageurl = "http://i.ytimg.com/vi/{$matches2[3]}/1.jpg"; 
 }
return $imageurl;
}

Suggested reading:


Posted in: WordPress
TAGS:, , , , , , , , , , , , , , ,
leave a comment.

Comments:

2 Comments

  1. Feb 13th, 2010

    Hi Vladimir,
    I'm trying to get the function to work, but I'm quite new to php and functions so can you be a littlebit more specific how I should implement it?
    Should I put something in between the parenthesis and if so, what exactly?
    Hope you can help me! Thanks.

  2. Oct 19th, 2009

    Oh... I've never thought we coulg get images from video.

Have your say

Your email is never published nor shared. Required fields are marked *

*
*

About

vladimir prelovac Vladimir Prelovac is CEO of Prelovac Media, a computer engineer by profession and an adventurer by state of mind. more +


"I would love to change the world, I just don't have the source code yet."

Services

Manage multiple WordPress sites

Built for WordPress enthusiasts, ManageWP helps you manage all your WordPress sites from one central location.

Books

WordPress Plugin Devleopment Book Read my book WordPress Plugin Development: Beginner's Guide

Published by Packt Publishing, available online through Amazon.