How to Create Certain Image Size Thumbnails for Custom Post Types Only
So, let’s imagine that your website has 10 registered custom post types, and each of them use 2-3 image sizes on the website pages. It is easy to understand that when we upload any picture on the website WordPress creates 20-30 copies of it!
There is no way to use add_image_size() for a custom post type but here is a small piece of code that solves this problem. This code tells WordPress when it have to create a certain resolution copy of the picture and when it doesn’t.
Both intermediate_image_sizes
and intermediate_image_sizes_advanced
hooks are OK for this task. A super simple example below, after you insert the code to your functions.php
file thumbnails my-image-size-name
won’t be created for images, uploaded from custom post type page
.
add_filter( 'intermediate_image_sizes_advanced', function( $sizes ){ if( isset( $_REQUEST['post_id'] ) && 'page' == get_post_type($_REQUEST['post_id'] ) ) { unset( $sizes['my-image-size-name'] ); } return $sizes; } );
A little bit more complicated example, but it is also correct:
/* * this hook will be fired while you uploading a picture */ add_filter( 'intermediate_image_sizes', 'misha_reduce_image_sizes' ); function misha_reduce_image_sizes( $sizes ){ /* * $sizes - all image sizes array Array ( [0] => thumbnail [1] => medium [2] => large [3] => post-thumbnail ) * get_post_type() to get post type */ $type = get_post_type($_REQUEST['post_id']); // $_REQUEST['post_id'] post id the image uploads to foreach( $sizes as $key => $value ){ /* * use switch if there are a lot of post types */ if( $type == 'page' ) { if( $value == 'regionfeatured' ){ // turn off 'regionfeatured' for pages unset( $sizes[$key] ); } } else if ( $type == 'region' ) { if( !in_array( $value, array('regionfeatured','misha335') ) ){ // for regions turn off everyting except 'regionfeatured' and 'misha335' unset( $sizes[$key] ); } } else { if( $value != 'thumbnail' ){ // turn off everything except thumbnail unset( $sizes[$key] ); } } } return $sizes; }