Support › Meta Box Builder › Responsive Images for the "Single Image" field typeResolved
I will use the CF type "Single Image" because my images are already in the WP library.
As for the Media Settings in WP, I customized the sizes as follows:
- Large: 1280x720
- Medium: 640x360
- Thumbnail: 240x135
So each of my images exists in 4 versions (1 original, 3 smaller generated by WP).
Now, let's say that I really want to optimize my site speed. One of the optimizations is to use image sizes that are proportionate to the user's device.
So here's my point: how to make sure that WP always calls/loads the most relevant size when I use the "Single Image" field type?
When outputting value for show image, you can use the second argument
array( 'size' => 'medium' ) in the helper function.
Get more details on the documentation https://docs.metabox.io/fields/single-image/#template-usage
It looks like your solution works manually. What if we want Meta Box to output the correct size automatically?
If you want to load the thumbnail based on the screen width, for example, on mobile load
thumbnail, on tablet load
medium, on desktop load
large. You can use the attribute
srcset of the
<img> tag. Get more details here https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images
Do you mind showing me how to do it in the PHP field of the Meta Box UI?
Thanks for being patient with me being a noob :-).
Here is the sample code to use the Art Direction, single_image field type, change the image size loaded based on the screen width.
<?php $thumbnail = rwmb_meta( 'single_image', array( 'size' => 'thumbnail' ) ); $large = rwmb_meta( 'single_image', array( 'size' => 'large' ) ); ?> <picture> <source media="(max-width: 799px)" srcset="<?php echo $thumbnail['url'] ?>"> <source media="(min-width: 800px)" srcset="<?php echo $large['url'] ?>"> <img src="<?php echo $large['url'] ?>" alt="Chris standing up holding his daughter Elva"> </picture>
You need to add the code to the corresponding template file in your theme folder.
Thank you Long! 🙂
Using Oxygen Builder, should I put it in a snippet in Advanced Scripts or Code Snippets?
Both Advanced Scripts and Code Snippets are ok. If you use the snippet plugin to implement the code, you need to create a shortcode then add the shortcode to the builder when creating the post. Refer to this document https://docs.metabox.io/extensions/meta-box-group/#outputing-group-with-page-builders
Thanks a lot Long, I really appreciate your support.