JavaScript for WordPress › Forums › Gutenberg Development › Getting specific image size from MediaUpload component
- This topic has 2 replies, 2 voices, and was last updated 3 years, 11 months ago by Alexis Villegas.
-
AuthorPosts
-
November 2, 2018 at 1:21 pm #63914middlesisterParticipant
I want to create a block for a employee listing page. Basically an image, name/title, phone number and email address field.
When I use the MediaUpload component, the src URL returned is to the full sized image. In PHP I would ask for a specific image size, i.e. thumbnail that is 300x300px.
I know I can set image dimensions in css, but it’s kinda ridiculous to resize a 4460x4460px image this way.
How can I get a specific image size from the javascript side?
I’ve been digging through the source of the gutenberg MediaUpload component, but my js skills are not strong enough yet to figure it out.
November 5, 2018 at 12:48 pm #64254middlesisterParticipantI found the solution, and I’m writing here so others can benefit.
If you inspect the object you get back from selecting the image, you’ll see all the properties and methods you have available. For the example block with Media Upload button, place your console.log inside the onSelectImage expression:
const onSelectImage = img => { console.log(img); …
The
sizes
property contains objects for all the available sizes. So to select a specific size the wholeonSelectImage
would become:const onSelectImage = img => { setAttributes({ imgID: img.id, imgURL: img.sizes.[SIZE NAME].url, imgAlt: img.alt, }); };
In my case
imgURL: img.sizes.thumbnail.url
Hope this helps anyone!
October 28, 2020 at 2:28 pm #148420Alexis VillegasParticipantThank 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 theimage_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!
- This reply was modified 3 years, 11 months ago by Alexis Villegas.
-
AuthorPosts
- You must be logged in to reply to this topic.