Last active
August 22, 2023 10:23
-
-
Save derekashauer/686cef44c3cd82bf4e07ea60f209ac1d to your computer and use it in GitHub Desktop.
WordPress: Make unique custom image size ONLY for featured image of a post
This file contains 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
add_action( 'save_post', 'custom_featured_image_size', 10, 2 ); | |
function custom_featured_image_size( $post_id, $post ) { | |
$image_size_name = 'my-custom-image-size'; | |
$cpt = 'my-cpt'; | |
$width = 1600; | |
$height = 1600; | |
$crop = false; | |
// Only for my CPT. | |
if ( $cpt != get_post_type( $post ) || ! has_post_thumbnail( $post_id ) ) { | |
return; | |
} | |
$featured_image_id = get_post_thumbnail_id( $post_id ); | |
$full_image_path = get_attached_file( $featured_image_id ); | |
$metadata = wp_get_attachment_metadata( $featured_image_id ); | |
// Check if image already exists, don't remake if it does. | |
if ( ! empty( $metadata['sizes'][ $image_size_name ]['file'] ) ) { | |
$existing_image_path = str_replace( wp_basename( $full_image_path ), wp_basename( $metadata['sizes'][ $image_size_name ]['file'] ), $full_image_path ); | |
if ( file_exists( $existing_image_path ) ) { | |
return; | |
} | |
} | |
// Make the new cover image and save to metadata. | |
$image_data = image_make_intermediate_size( $full_image_path, $width, $height, $crop ); | |
$metadata['sizes'][ $image_size_name ] = $image_data; | |
wp_update_attachment_metadata( $featured_image_id, $metadata ); | |
} |
This file contains 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
// How to use this in your theme | |
the_post_thumbnail( 'my-custom-image-size' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment