Responsive Images
- This topic has 2 replies, 2 voices, and was last updated 8 years, 10 months ago by
Martin.
Viewing 3 posts - 1 through 3 (of 3 total)
-
AuthorPosts
-
June 7, 2016 at 6:15 AM #3377
Martin
ParticipantHi,
I'm trying to use the srcset and sizes information for displaying the images in the front-end.The only thing left I have to do is to display the sizes, I get an Array as a value.
page-template-gallery.php
<?php $images = rwmb_meta( 'your_prefix_imgadv', 'size=full' ); if ( !empty( $images ) ) { foreach ( $images as $image ) { echo "\n<a href='{$image['full_url']}'>\n<img src='{$image['url']}' width='{$image['width']}' height='{$image['height']}' alt='{$image['alt']}' srcset='{$image['srcset']}' sizes='{$image['sizes']}'>\n</a>"; } } ?>
When I view the source code I get this
<img src='http://localhost/wordpress/wp-content/uploads/2016/06/hero-01.jpg' width='1680' height='740' alt='Hero image 1' srcset='http://localhost/wordpress/wp-content/uploads/2016/06/hero-01-300x132.jpg 300w, http://localhost/wordpress/wp-content/uploads/2016/06/hero-01-768x338.jpg 768w, http://localhost/wordpress/wp-content/uploads/2016/06/hero-01-1024x451.jpg 1024w' sizes='Array'>
What do I need to modify in the template file to display the sizes array values?
Thanks!
June 7, 2016 at 8:29 AM #3378Anh Tran
KeymasterHi, the
sizes
value returned is not thesizes
attribute in responsive image. It's an array of the following info:[sizes] => Array ( [thumbnail] => Array ( [file] => press_image-150x150.jpg [width] => 150 [height] => 150 [mime-type] => image/jpeg ) [medium] => Array ( [file] => press_image-4-300x194.jpg [width] => 300 [height] => 194 [mime-type] => image/jpeg ) [large] => Array ( [file] => press_image-1024x665.jpg [width] => 1024 [height] => 665 [mime-type] => image/jpeg ) [post-thumbnail] => Array ( [file] => press_image-624x405.jpg [width] => 624 [height] => 405 [mime-type] => image/jpeg ) )
To get the
sizes
attribute, we can use the following function:wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null, $attachment_id = 0 )
So, in your code, you can do like this:
foreach ( $images as $image ) { $sizes = wp_calculate_image_sizes( array( $image['width'], $image['height'] ), null, null, $image['ID'] ); echo "\n<a href='{$image['full_url']}'>\n<img src='{$image['url']}' width='{$image['width']}' height='{$image['height']}' alt='{$image['alt']}' srcset='{$image['srcset']}' sizes='{$sizes}'>\n</a>"; }
June 7, 2016 at 9:50 PM #3387Martin
ParticipantThanks so much! Keep up the good work 🙂
Cheers!
Martin. -
AuthorPosts
Viewing 3 posts - 1 through 3 (of 3 total)
- The topic ‘Responsive Images’ is closed to new replies.