Created
September 22, 2015 16:28
-
-
Save shazahm1/763bc885070f84d69bce to your computer and use it in GitHub Desktop.
If no featured image... Grab the first image in the post content.. Or generate a thumbnail based on youtube or vimeo video if that is included instead of an image... then save the image as featured image...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Retrieves the thumbnail URL to use for a post | |
* @param string $text The body of the post (get_content) | |
* @param string $size The image size to retrieve | |
* @return string The image URL to use | |
*/ | |
function get_thumb_url($text, $size){ | |
global $post; | |
$imageurl = FALSE; | |
$needs_resize = TRUE; | |
// 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); | |
if ($img_src!==FALSE) { | |
$imageurl = $img_src[0]; | |
$needs_resize = FALSE; | |
} | |
// 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 image | |
$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= array_key_exists(1, $matches) ? $matches[1] : FALSE; | |
} | |
// If there's no image attached or inserted in the post, look for a YouTube video | |
if (!$imageurl){ | |
preg_match("/([a-zA-Z0-9\-\_]+\.|)youtube\.com\/watch(\?v\=|\/v\/)([a-zA-Z0-9\-\_]{11})([^<\s]*)/", $text, $matches); | |
$youtubeurl = array_key_exists(0, $matches) ? $matches[0] : FALSE; | |
$videokey = array_key_exists(3, $matches) ? $matches[3] : FALSE; | |
if (!$youtubeurl) { | |
preg_match("/([a-zA-Z0-9\-\_]+\.|)youtu\.be\/([a-zA-Z0-9\-\_]{11})([^<\s]*)/", $text, $matches); | |
$youtubeurl = array_key_exists(0, $matches) ? $matches[0] : FALSE; | |
$videokey = array_key_exists(2, $matches) ? $matches[2] : FALSE; | |
} | |
if ($youtubeurl) | |
$imageurl = "http://i.ytimg.com/vi/{$videokey}/0.jpg"; | |
} | |
// If there's no image attached or insert in the post, and no youtube video, look for a Vimeo video: | |
if (!$imageurl){ | |
$pieces = explode(" ", $text); | |
foreach ($pieces as $piece) { | |
if (preg_match("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", $piece)) { | |
$videokey = get_vimeoid( $piece ); | |
if( !empty($videokey) ) break; | |
} | |
} | |
if ($videokey) | |
$imageurl = getVimeoThumb( $videokey ); | |
} | |
if ($needs_resize===TRUE) { | |
$imageurl = resize_and_save_image($imageurl, $size); | |
} | |
// Spit out the image path | |
return $imageurl; | |
} | |
function getVimeoThumb($id) { | |
$data = file_get_contents("http://vimeo.com/api/v2/video/$id.json"); | |
$data = json_decode($data); | |
return $data[0]->thumbnail_medium; | |
} | |
function get_vimeoid( $url ) { | |
$regex = '~ | |
# Match Vimeo link and embed code | |
(?:<iframe [^>]*src=")? # If iframe match up to first quote of src | |
(?: # Group vimeo url | |
https?:\/\/ # Either http or https | |
(?:[\w]+\.)* # Optional subdomains | |
vimeo\.com # Match vimeo.com | |
(?:[\/\w]*\/videos?)? # Optional video sub directory this handles groups links also | |
\/ # Slash before Id | |
([0-9]+) # $1: VIDEO_ID is numeric | |
[^\s]* # Not a space | |
) # End group | |
"? # Match end quote if part of src | |
(?:[^>]*></iframe>)? # Match the end of the iframe | |
(?:<p>.*</p>)? # Match any title information stuff | |
~ix'; | |
preg_match( $regex, $url, $matches ); | |
return $matches[1]; | |
} | |
/** | |
* Creates a resized image, attaches it to the parent post as a featured image | |
* @param string $url The URL of the image to resize | |
* @param string $size The image size (e.g. 'thumbnail', 'medium') | |
* @return string The resized image's URL | |
*/ | |
function resize_and_save_image($url, $size) { | |
global $post; | |
$image = wp_get_image_editor($url); | |
if (!is_wp_error($image)) { | |
// Loads dimensions for the custom size | |
extract(get_image_crop_dimensions($size)); | |
// Determines the location where the new image should be saved | |
$upload_dir = wp_upload_dir(); | |
$path = $upload_dir['path']; | |
$dest = $image->generate_filename($width.'x'.$height, $path); | |
// Resizes and saves the new image | |
$image->resize($width, $height, $crop); | |
$image->save($dest); | |
// Saves the new image in the media library | |
$wp_filetype = wp_check_filetype(basename($dest), NULL); | |
$attachment = array( | |
'guid' => $upload_dir['url'] . '/' . basename($dest), | |
'post_mime_type' => $wp_filetype['type'], | |
'post_title' => preg_replace('/\.[^.]+$/', '', basename($dest)), | |
'post_content' => '', | |
'post_status' => 'inherit' | |
); | |
$attach_id = wp_insert_attachment($attachment, $dest, $post->ID); | |
// Includes image.php so wp_generate_attachment_metadata() will work | |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
$attach_data = wp_generate_attachment_metadata($attach_id, $dest); | |
wp_update_attachment_metadata($attach_id, $attach_data); | |
// Sets the new image as the post's featured image | |
update_post_meta($post->ID, '_thumbnail_id', $attach_id); | |
// Returns the new source | |
$new_url = wp_get_attachment_image_src($attach_id, $size); | |
return $new_url[0]; | |
} else { | |
return FALSE; | |
} | |
} | |
/** | |
* Retrieves the dimensions for a given image size | |
* @param string $size The image size (e.g. 'thumbnail', 'medium') | |
* @return array The width, height, and crop values for the image size | |
*/ | |
function get_image_crop_dimensions( $size ) { | |
// Checks if the image is one of the default WP sizes | |
if (in_array($size, array('thumb', 'medium', 'large'))) { | |
$width = get_option($size . '_size_w'); | |
$height = get_option($size . '_size_h'); | |
$crop = $size==='thumb' ? TRUE : FALSE; | |
} else { | |
// Loads the custom image sizes | |
global $_wp_additional_image_sizes; | |
if (array_key_exists($size, $_wp_additional_image_sizes)) { | |
$width = $_wp_additional_image_sizes[$size]['width']; | |
$height = $_wp_additional_image_sizes[$size]['height']; | |
$crop = $_wp_additional_image_sizes[$size]['crop']; | |
} else { | |
// Without a match, the thumbnail size is the default | |
$width = get_option('thumb_size_w'); | |
$height = get_option('thumb_size_h'); | |
$crop = TRUE; | |
} | |
} | |
return array( | |
'width' => $width, | |
'height' => $height, | |
'crop' => $crop, | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment