Хорошо, это будет выглядеть как огромный дамп данных, потому что, честно говоря, это то, что он есть.Сейчас у меня нет времени, чтобы перефразировать каждую часть этого, но это именно та проблема, с которой я столкнулся год назад, когда создавал тему для огромной многосайтовой сети с некоторыми очень старыми постами.Первая функция является основной, и она вызывает некоторые другие для выполнения различных действий.Я привожу его здесь не как полный ответ, а как ресурс или пример для просмотра, если у вас есть время.Вы можете увидеть несколько способов исправить или перестроить вашу функцию здесь.
Надеюсь, вы найдете это полезным:
/**
* Gets the featured image.
* If no featured image, picks up the first image in the post
* If no images, default image is used
*
* @param int $post_id
* @param bool $thumb_size
* @param bool $return_all_images
*
* @return string|array Returns the url of the image to use, or an array if return_all_images is true
*/
function e3_featured_image($post_id, $thumb_size = false, $return_all_images = false) {
$the_post = get_post($post_id);
if ( ! $thumb_size ) {
$thumb_size = 'e3-blog-featured-thumbnail';
}
if ( $the_post ) {
$remote_images = $local_images = $remote_images_parsed = array();
$thumbnail_url = '';
if ( ! $thumbnail_url && $url = get_the_post_thumbnail_url( $the_post, $thumb_size ) ) {
// The featured image is set. Use that.
if ( ! $return_all_images ) {
return $url;
} else {
$thumbnail_url = $url;
}
}
// Now move on to checking the content
if ( preg_match_all( "/<img\s[^>]*src=[\"']([^\"']*)[\"'][^>]*>/", $the_post->post_content, $matches ) ) {
foreach ( $matches[1] as $key => $url ) {
$components = parse_url( $url );
$relative = ( ! $components['host'] );
if ( $relative || is_local_attachment( $url ) || strtolower( $components['host'] ) == strtolower( $_SERVER['HTTP_HOST'] ) ) {
// Ok, we've got a local image. Find it's attachment info.
$return = e3_featured_image_do_lookup( $matches[0][ $key ], $url, $thumb_size );
if ( $return && ! $return_all_images ) {
return $return;
} elseif ( $return ) {
$local_images[] = $return;
continue;
}
// Couldn't find the image in the database, so let's treat it as a remote image
$remote_images[] = $url;
} else {
// Store remote image
$remote_images[] = $url;
}
}
}
if ( count( $remote_images ) > 0 ) {
// There were no local images. Try getting a thumbnail from a remote image.
foreach ( $remote_images as $image ) {
$return = e3_get_remote_thumbnail( $image, $thumb_size );
if ( $return && ! $return_all_images ) {
return $return;
} elseif ( $return ) {
$remote_images_parsed[] = $return;
continue;
}
}
}
}
if ( $return_all_images ) {
$return_array = array();
if ( ! empty( $thumbnail_url ) ) {
$return_array['featured_image'] = $thumbnail_url;
}
if ( ! empty( $local_images ) ) {
$return_array['local_images'] = $local_images;
}
if ( ! empty( $remote_images_parsed ) ) {
$return_array['remote_images'] = $remote_images_parsed;
}
if ( !empty( $return_array) ) {
return $return_array;
}
}
// Still here? Return default image
if ( file_exists( __DIR__ . "/img/default-{$thumb_size}.jpg") ) {
return get_stylesheet_directory_uri() . "/img/default-{$thumb_size}.jpg";
} else {
return get_stylesheet_directory_uri() . '/img/default-blog-image.jpg';
}
}
/**
* See if we can find the db entry for an image so we can return the right thumb_size
*
* @param string $img_tag The entire img tag
* @param string $url The URL of the image
* @param string $thumb_size Thumbnail size (WP slug)
*
* @return bool|false|string
*/
function e3_featured_image_do_lookup($img_tag, $url, $thumb_size) {
// First, try url_to_postid()
if ( $id = url_to_postid($url) ) {
$post = get_post( $id );
if ( 'attachment' == $post->post_type ) {
return wp_get_attachment_image_url( $id, $thumb_size );
}
}
// Next, look for the WP class that has the ID in it
if ( preg_match( "/wp-image-([0-9]+)/i", $img_tag, $class_match) ) {
// We found the ID...
$post = get_post( $class_match[1] );
if ( 'attachment' == $post->post_type ) {
return wp_get_attachment_image_url( $class_match[1], $thumb_size );
}
}
// Try the guid
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid LIKE '%%%s%%';", $url ));
$post = get_post($attachment[0]);
if ( 'attachment' == $post->post_type ) {
return wp_get_attachment_image_url( $attachment[0], $thumb_size );
}
return false;
}
/**
* Returns the URL of a local copy of a remote image, sized appropriately
*
* @param string $url URL of the remote image
* @param string|array $size An array where 0=>width (px), 1=>height (px) and 2=>crop (bool)
* -OR-
* Name of a WP registered timage size
* @param null|bool $crop Whether to crop the image to the exact size. Overrides crop value
* of $size
*
* @return bool|string
*/
function e3_get_remote_thumbnail( $url, $size, $crop = null ) {
if ( is_array($size) ) {
if ( isset($size[0]) && isset($size[1]) ) {
$width = intval($size[0]);
$height = intval($size[1]);
if ( isset( $size[2] ) && null == $crop ) {
$crop = $size[2];
}
} else {
// Size was an array, but we can't find the width/height
return false;
}
} else {
$sizes = wp_get_additional_image_sizes();
if ( isset( $sizes[$size] ) ) {
$width = intval($sizes[$size]['width']);
$height = intval($sizes[$size]['height']);
$crop = ($crop === null) ? $sizes[$size]['crop'] : $crop;
} else {
// Size wasn't an array and didn't match any registered image sizes. Give up.
return false;
}
}
if ( ! $width && ! $height ) {
//Can't make an image with no width or height.
return false;
}
// Figure out filenames
$width_text = $width ? $width : '_';
$height_text = $height ? $height : '_';
$crop = $crop ? '1' : '0';
$extension = strtolower( substr($url, strripos($url, '.') + 1) );
if ( ! in_array( $extension, array('jpg', 'jpeg', 'png', 'gif') ) ) {
// Not a supported image type (jpeg, png or gif).
return false;
}
$upload_dir = wp_upload_dir();
if ( ! file_exists( $upload_dir['basedir'] . '/cache' ) ) {
mkdir( $upload_dir['basedir'] . '/cache' );
}
if ( ! file_exists( $upload_dir['basedir'] . '/cache/e3_external_thumbs/' ) ) {
mkdir( $upload_dir['basedir'] . '/cache/e3_external_thumbs/' );
}
$cache_file_ending = '/cache/e3_external_thumbs/' . md5($url) . "-$height_text-$width_text-$crop.$extension";
$cache_file_path = $upload_dir['basedir'] . $cache_file_ending;
$cache_file_uri = $upload_dir['baseurl'] . $cache_file_ending;
// Check cache for this url and size
if ( file_exists($cache_file_path) ) {
if ( 0 == filesize($cache_file_path) ) {
// This file has been cached as an empty file. Just return false because it seems like a bad link
return false;
}
return $cache_file_uri;
}
// Get, resize, cache and return the remote image
// --Get
$file = file_get_contents( $url );
if ( ! $file ) {
// Looks like the image doesn't exist. Save a blank file to keep this from gumming up the works on every page load
file_put_contents($cache_file_path, '');
return false;
} else {
file_put_contents('tmp.image', $file );
}
// --Resize and cache
$crop_result = e3_resize_crop_image($width, $height, 'tmp.image', $cache_file_path, $crop );
if ( file_exists( 'tmp.image' ) ) {
unlink( 'tmp.image' );
}
if ( ! $crop_result ) {
// The crop failed due to mime type problem. Save a blank file
file_put_contents($cache_file_path, '');
return false;
}
// --Return
return $cache_file_uri;
}
/**
* Resize/Crop and save an image
*
* @param int $max_width Width (or max width if crop is false) for new image
* @param int $max_height Height (or max height if crop is false) for new image
* @param string $source_file Image to crop
* @param string $dst_file Path and filename to save the new image to
* @param bool $crop Whether to crop to exact dimensions
*
* @return bool
*/
function e3_resize_crop_image($max_width, $max_height, $source_file, $dst_file, $crop){
$quality = 80;
$imgsize = getimagesize($source_file);
$width = $imgsize[0];
$height = $imgsize[1];
if ( ! $max_height ) {
$max_height = $max_width * $height / $width;
}
if ( ! $max_width ) {
$max_width = $max_height * $width / $height;
}
$mime = $imgsize['mime'];
if ( $width < $max_width && $height < $max_height ) {
copy( $source_file, $dst_file );
if ( file_exists( 'tmp.image' ) ) {
unlink( 'tmp.image' );
}
return true;
}
switch($mime){
case 'image/gif':
$image_create = "imagecreatefromgif";
$image = "imagegif";
break;
case 'image/png':
$image_create = "imagecreatefrompng";
$image = "imagepng";
$quality = 7;
break;
case 'image/jpeg':
$image_create = "imagecreatefromjpeg";
$image = "imagejpeg";
break;
default:
return false;
break;
}
$dst_img = imagecreatetruecolor( $max_width, $max_height );
// set background to white
$white = imagecolorallocate($dst_img, 255, 255, 255);
imagefill($dst_img, 0, 0, $white);
$src_img = $image_create($source_file);
$ratio = $width / $height;
$new_ratio = $max_width / $max_height;
if ( $ratio == $new_ratio ) {
// Same ratio, just resize
imagecopyresampled( $dst_img, $src_img, 0, 0, 0, 0, $max_width, $max_height, $width, $height );
} elseif ( ! $crop ) {
// Don't crop the image. Just resize to fit inside the box
if ( $ratio > $new_ratio ) {
// Image is wider than the new image
// New image has requested width, but a reduced height
$new_height = floor( $max_width / $ratio );
$top = round( ($max_height - $new_height) / 2 );
//$dst_img = imagecreatetruecolor( $max_width, $new_height );
imagecopyresampled( $dst_img, $src_img, 0, $top, 0, 0, $max_width, $new_height, $width, $height );
} else {
// Image is taller than the new image
// New image has requested height, but a reduced wodth
$new_width = floor( $max_height * $ratio );
$left = round( ($max_width - $new_width) / 2 );
//$dst_img = imagecreatetruecolor( $new_width, $max_height );
imagecopyresampled( $dst_img, $src_img, $left, 0, 0, 0, $new_width, $max_height, $width, $height );
}
} else {
// Crop the image to fit exactly
if ( $ratio > $new_ratio ) {
// Image is wider than the new image
// Keep the height and crop the sides off
$new_original_width = floor( $height * $new_ratio );
$horizontal_cut_point = ($width - $new_original_width) / 2;
imagecopyresampled( $dst_img, $src_img, 0, 0, $horizontal_cut_point, 0, $max_width, $max_height, $new_original_width, $height );
} else {
// Image is taller than the new image
// keep the width and crop the top and bottom off
$new_original_height = floor( $width / $new_ratio );
$vertical_cut_point = ($height - $new_original_height) / 2;
imagecopyresampled( $dst_img, $src_img, 0, 0, 0, $vertical_cut_point, $max_width, $max_height, $width, $new_original_height );
}
}
$image( $dst_img, $dst_file, $quality );
if ( $dst_img ) {
imagedestroy($dst_img);
}
if ( $src_img ) {
imagedestroy($src_img);
}
return true;
}