JavaScript for WordPress Forums Gutenberg Development Getting specific image size from MediaUpload component Reply To: Getting specific image size from MediaUpload component

#148420
Alexis Villegas
Participant

Thank you @kairn this was really helpful!

I want to add that if you want to use a custom image size added through add_image_size it would not be immediately available to the JS object. You’ll have to add the new image sizes using the image_size_names_choose filter in PHP like this:

add_filter( 'image_size_names_choose', 'myprefix_custom_image_sizes' );
/**
 * Add new image sizes to list of default image sizes so they can be
 * accessed in JS and wp_prepare_attachment_for_js().
 *
 * @param  array $size_names An array containing default image sizes and their names.
 * @return array $size_names Merged array containing new image sizes and their names.
 */
function myprefix_custom_image_sizes( $size_names ) {
	
    // Add new image sizes to array.
    $new_size_names = array(
        'featured-image'    => esc_html__( 'Featured Image', 'my-text-domain' ),
        'portfolio-archive' => esc_html__( 'Portfolio Archive', 'my-text-domain' ),
    );
	
    // Combine the two arrays.
    $size_names = array_merge( $new_size_names, $size_names );
	
    return $size_names;
	
}

After, you’ll be able to access the image size using img.sizes.portfolio-archive.url for example.

Hope this can add to @kairn excellent post above!