Restrict thumbnail sizes by post types. WordPress function open

Restrict thumbnail sizes by post types. WordPress function

Tested: WordPress 5+

By default, when you create a post in WordPress and add a thumbnail to it, 3 new images with different sizes are automatically created.
You can also add your own custom sizes to WordPress, then when creating a post, instead of 3 new images, 10 will be created!
This will quickly fill up your disk, and will put an additional load on your site.

To avoid this. Create only the necessary image sizes for each required post type.

The code below will help you with this:

add_filter( 'intermediate_image_sizes', 'vishivka_reduce_image_sizes' );
 
function vishivka_reduce_image_sizes( $sizes ){
	/*
	 * $sizes - all image sizes array Array ( [0] => thumbnail [1] => medium [2] => large [3] => post-thumbnail [4] => customsize [5] => customsize2)
	 */
	$type = get_post_type($_REQUEST['post_id']); // $_REQUEST['post_id'] post id the image uploads to
 
	foreach( $sizes as $key => $value ){
 
		if( $type == 'page' ) { //if you upload image to entry from post type "page"
			if( $value == 'customsize' ){ // turn off "customsize" size for "page" posts
    				unset( $sizes[$key] );
    			}
		} else if ( $type == 'rent' ) {//if you upload image to entry from post type "book"
			if( !in_array( $value, array('customsize','thumbnail') ) ){ // off everyting except "customsize" and "thumbnail"
    				unset( $sizes[$key] );
    			}
		} else {
			if( $value != 'thumbnail' ){ // turn off every sizes except thumbnail for all another
    				unset( $sizes[$key] );
    			}
		}
	}
	return $sizes;
}
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation