Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.