I am currently trying to create a custom image size for WordPress. I am uploading my full size image (1,000px by 1,000px) using the Media Library, and trying to use the function
's below in my functions.php
file.
As you can see, I am trying to save another version that is exactly 50% of the original image's width
and height
. The function
below is saving a new version, but it is using WordPress' medium_large
(768px by 768px) image, which results in my image being saved at 384px by 384px instead of the desired 500px by 500px.
I tried changing WordPress' default medium_large
size to 2000px by 2000px, but then the function
below switched to using WordPress' thumbnail
(150px by 150px) image, resulting in a 75px by 75px image.
How do I get the code below to use the original
image, not one of WordPress' created image sizes (medium_large
, thumbnail
, etc)?
<?php
add_filter('wp_generate_attachment_metadata', 'half_size_attachment_meta', 10, 2);
function half_size_attachment_meta($metadata, $attachment_id) {
foreach($metadata as $key => $value) {
if (is_array($value)) {
foreach($value as $image => $attr) {
if (is_array($attr))
half_size_create_images(get_attached_file($attachment_id), $attr['width'], $attr['height'], true);
}
}
}
return $metadata;
}
function half_size_create_images($file, $width, $height, $crop = false) {
if ($width || $height) {
$resized_file = wp_get_image_editor($file);
if (!is_wp_error($resized_file)) {
$filename = $resized_file - > generate_filename($width.
'x'.$height.
'-sml');
$resized_file - > resize($width * 0.5, $height * 0.5, $crop);
$resized_file - > save($filename);
$info = $resized_file - > get_size();
return array(
'file' => wp_basename($filename),
'width' => $info['width'],
'height' => $info['height'],
);
}
}
return false;
}
?>
Edit: I am not looking to use add_image_size
/ the_post_thumbnail
within the functions.php file. This doesn't force the creation of images, and doesn't allow for percentage based values.
</div>
Create your new image size with builtin WP function add_image_size
https://developer.wordpress.org/reference/functions/add_image_size/
then call it with the_post_thumbnail
function https://developer.wordpress.org/reference/functions/the_post_thumbnail/