Skip to content

Instantly share code, notes, and snippets.

@pulcix
Last active September 22, 2015 16:20
Show Gist options
  • Select an option

  • Save pulcix/b5b186a69a84ce7b8e41 to your computer and use it in GitHub Desktop.

Select an option

Save pulcix/b5b186a69a84ce7b8e41 to your computer and use it in GitHub Desktop.
Grab a thumbnail for post... If no featured image... Grab the first image in the post content.. Or generate a thumbnail based on youtube video if that is included instead of an image...
<?php
function rw_thumb_url($text, $size){
global $post;
$imageurl = "";
// Check to see which image is set as "Featured Image"
$featuredimg = get_post_thumbnail_id( $post->ID );
// Get source for featured image
$img_src = wp_get_attachment_image_src( $featuredimg, $size );
// Set $imageurl to Featured Image
$imageurl = $img_src[0];
// If there is no "Featured Image" set, move on and get the first image attached to the post
if ( !$imageurl ) {
// Extract the thumbnail from the first attached imaged
$allimages = get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . $post->ID );
foreach ( $allimages as $img ) {
$img_src = wp_get_attachment_image_src( $img->ID, $size );
break;
}
// Set $imageurl to first attached image
$imageurl = $img_src[0];
}
// If there is no image attached to the post, look for anything that looks like an image and get that
if ( !$imageurl ) {
preg_match( '/<\s*img [^\>]*src\s*=\s*[\""\']?([^\""\'>]*)/i' , $text, $matches );
$imageurl = $matches[1];
}
// If there's no image attached or inserted in the post, look for a YouTube video
if ( !$imageur l) {
preg_match( "/([a-zA-Z0-9\-\_]+\.|)youtube\.com\/watch(\?v\=|\/v\/)([a-zA-Z0-9\-\_]{11})([^<\s]*)/", $text, $matches2 );
$youtubeurl = $matches2[0];
$videokey = $matches2[3];
if ( !$youtubeurl ) {
preg_match( "/([a-zA-Z0-9\-\_]+\.|)youtu\.be\/([a-zA-Z0-9\-\_]{11})([^<\s]*)/", $text, $matches2 );
$youtubeurl = $matches2[0];
$videokey = $matches2[2];
}
if ( $youtubeurl )
$imageurl = "http://i.ytimg.com/vi/{$videokey}/0.jpg";
}
// Spit out the image path
return $imageurl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment