Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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 rw_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 ($needs_resize===TRUE) {
$imageurl = resize_and_save_image($imageurl, $size);
}
// Spit out the image path
return $imageurl;
}
/**
* 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