Generate a Custom Image Size Only for One Post Type
Registers an image size, such as a wide portfolio banner, but only creates it for images uploaded to that post type, so every other upload is not stored in yet another size.
Opens WPIDE on
Code
// Image size and the only post type that gets it.
$wpide_type_size_name = 'portfolio-banner';
$wpide_type_size_width = 1600;
$wpide_type_size_height = 700;
$wpide_type_size_post_type = 'portfolio';
add_action( 'after_setup_theme', function () use ( $wpide_type_size_name, $wpide_type_size_width, $wpide_type_size_height ) {
add_image_size( $wpide_type_size_name, $wpide_type_size_width, $wpide_type_size_height, true );
} );
add_filter( 'intermediate_image_sizes_advanced', function ( $sizes, $metadata, $attachment_id = 0 ) use ( $wpide_type_size_name, $wpide_type_size_post_type ) {
$parent = $attachment_id ? (int) wp_get_post_parent_id( $attachment_id ) : 0;
if ( ! $parent && isset( $_REQUEST['post_id'] ) ) {
$parent = absint( $_REQUEST['post_id'] );
}
if ( ! $parent || get_post_type( $parent ) !== $wpide_type_size_post_type ) {
unset( $sizes[ $wpide_type_size_name ] );
}
return $sizes;
}, 10, 3 );
Notes
The size is created when you upload from inside a post of that type (the image is "attached" to it); set the name, dimensions and post type below.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.