Resize image with WordPress – custom sizes

By , last updated March 27, 2015

Sometimes when creating, developing and maintaining a blog in the WordPress platform, you’ll need to customize it.

Here is a small snippet which you can put in your plugin or your theme to enable custom image sizes with custom names.

// Pre-defined image sizes
if ( function_exists( 'add_image_size' ) )
{
	add_image_size( 'size-8192', 8192, 8192, false ); //(soft cropped)
	add_image_size( 'size-4096', 4096, 4096, false ); //(soft cropped)
	add_image_size( 'size-2048', 2048, 2048, false ); //(soft cropped)
	add_image_size( 'size-1024', 1024, 1024, false ); //(soft cropped)
	add_image_size( 'size-512', 512, 512, false ); //(soft cropped)
	add_image_size( 'size-256', 256, 256, false ); //(soft cropped)
}

// Enables pretty names for the sizes
add_filter('image_size_names_choose', 'my_image_sizes');
add_filter('jpeg_quality', function($arg){return 100;});
add_filter('wp_editor_set_quality', function($arg){return 100;});

// Callback for pretty image size names
function my_image_sizes($sizes)
{
	$addsizes = array(
		"size-8192" => __( "Size 8192"),
		"size-4096" => __( "Size 4096"),
		"size-2048" => __( "Size 2048"),
		"size-1024" => __( "Size 1024"),
		"size-512"  => __( "Size 512" ),
		"size-256"  => __( "Size 256" ),
	);

	$newsizes = array_merge($sizes, $addsizes);
	return $newsizes;
}

It’s rather simple, once you know how. I always forget the exact syntax and name of the methods in the WordPress framework, but here it is.

The code is self-explainatory, but here is a short primer. To begin with, the image sizes is added to the WordPress engine. Then some filters (hooks) are registered and finally the callback with the pretty names of the image sizes.

Comments

Be the first to comment.

Leave a Reply


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*