Created
February 29, 2024 15:37
-
-
Save rhcarlosweb/d030824b5f51d060bd927e443b126bd6 to your computer and use it in GitHub Desktop.
Crop image wordpress
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 function rh_image_size($attachment_id, $width = null, $height = null, $crop = true, $force_crop = false) { | |
$path = get_attached_file($attachment_id); | |
if (!file_exists($path)) { | |
return false; | |
} | |
$upload = wp_upload_dir(); | |
$path_info = pathinfo($path); | |
$base_url = $upload['baseurl'] . str_replace($upload['basedir'], '', $path_info['dirname']); | |
$meta = wp_get_attachment_metadata($attachment_id); | |
$key = sprintf('resized-%dx%d', $width, $height); | |
// If the size already exists and force_crop is true, remove it before creating a new one | |
if ($force_crop && isset($meta['sizes'][$key])) { | |
$old_file = $upload['basedir'] . str_replace($upload['baseurl'], '', "{$base_url}/{$meta[ 'sizes' ][ $key ]['file']}"); | |
if (file_exists($old_file)) { | |
unlink($old_file); | |
} | |
unset($meta['sizes'][$key]); | |
} | |
// If the size already exists and force_crop is false, return the existing size | |
if (!$force_crop && isset($meta['sizes'][$key])) { | |
return "{$base_url}/{$meta[ 'sizes' ][ $key ]['file']}"; | |
} | |
// Generate new size | |
$resized = image_make_intermediate_size($path, $width, $height, $crop); | |
if ($resized && !is_wp_error($resized)) { | |
// Let metadata know about our new size. | |
$meta['sizes'][$key] = $resized; | |
wp_update_attachment_metadata($attachment_id, $meta); | |
return "{$base_url}/{$resized['file']}"; | |
} | |
// Return original if fails | |
return "{$base_url}/{$path_info['basename']}"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment