Even though we create our image size we will need additional code to add it into the Media Uploaders dropdown of available sizes. First let's register the size. We can use the init
or after_setup_theme
hook:
function theme_init() {
add_image_size( 'banner_image', 1200, 200, true );
}
add_action( 'init', 'theme_init' );
We need to use the image_size_names_choose
hook to add in the new size into the available sizes. The Developer Resources suggests using the following:
/**
* @param Array $default_sizes - Array( 'size_slug' => 'Size Title' )
*
* @return Array $default_sizes
*/
function image_sizes_to_mediapicker( $default_sizes ) {
return array_merge( $default_sizes, array(
'banner_image' => __( 'Banner Image' ),
) );
}
add_filter( 'image_size_names_choose', 'image_sizes_to_mediapicker' );
The above works fine but maybe we can automate this a bit. The below assumes that any additional sizes are named with underscores so it may not be an optimal solution that works with plugins that add their own sizes. It is also heavily commented to show what each variable is.
/**
* @param Array $default_sizes - Array( 'size_slug' => 'Title' )
*
* @return Array $return_sizes
*/
function image_sizes_to_mediapicker( $default_sizes ) {
global $_wp_additional_image_sizes; // All additionally added sizes
$size_slugs = array_keys( $_wp_additional_image_sizes ); // Get array of additional sizes
$default_slugs = array_keys( $default_sizes ); // Get array of default sizes
$exclude_sizes = array( 'medium_large' ); // Exclude any image sizes
// $exclude_sizes = get_option( 'mediapicker_exlcuded_sizes', array() ) // IF we want to previously set / retrieve an array of excluded options
$sizes_needed = array_diff( $size_slugs, $default_slugs, $exclude_sizes ); // Get difference between the defaults and additional sizes
$return_sizes = $default_sizes; // Let's keep separation between passed and returned
foreach( $sizes_needed as $size_slug ) {
$pretty_title = ucwords( str_replace( '_', ' ', $size_slug ) ); // Create a pretty title
$return_sizes[ $size_slug ] = __( $pretty_title );
}
return $return_sizes;
}
add_filter( 'image_size_names_choose', 'image_sizes_to_mediapicker' );