[WP] Using WordPress responsive images
Since version 4.4 WordPress supports responsive images. To use this feature in RoyalSlider, you need to modify slide markup.
Step 1: go to your theme functions.php and add such code:
function newrs_add_resp_img_variable($m, $slide_data, $options) {
$m->addHelper('responsive_image_tag', function() use ($slide_data) {
$attachment_id = 0;
if (is_object($slide_data) && isset($slide_data->ID) ) {
if ( get_post_type($slide_data) === 'attachment' ) {
$attachment_id = $slide_data->ID;
} else {
$featured_image_id = get_post_thumbnail_id($slide_data->ID);
if ($featured_image_id) {
$attachment_id = $featured_image_id;
}
}
} else if( isset($slide_data['image']) && isset($slide_data['image']['attachment_id']) ) {
$attachment_id = $slide_data['image']['attachment_id'];
}
if( $attachment_id ) {
$att_src = wp_get_attachment_image_url( $attachment_id, 'large' );
$att_srcbig = wp_get_attachment_image_url( $attachment_id, 'full' );
$att_srcset = wp_get_attachment_image_srcset( $attachment_id, 'large' );
$att_alt = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
return '<img src="'.$att_src.'" data-rsBigImg="'.$att_srcbig.'" srcset="'.$att_srcset.'" alt="'.$att_alt.'" />';
}
return '{{image_tag}}';
} );
}
add_filter('new_rs_slides_renderer_helper','newrs_add_resp_img_variable', 10, 4);
It'll create {{responsive_image_tag}}
variable that will work for "custom" slider, as well as for "gallery" type of slider.
Step 2: go to slider General Options, click Edit Slide Markup and instead of {{image_tag}}
, add {{responsive_image_tag}}
.
Step 3: optionally style the image, since default JS-based scaling will not apply, for example to make images fit into slide:
.rsSlide img {
display: block;
height: 0;
max-height: 100%;
max-width: 100%;
min-height: 100%;
min-width: 100%;
width: 0;
margin: auto;
}
Note:
- This method isn't supported for 500px, Flickr or Instagram sliders, as images are resized by third-party service.
- This method doesn't support lazy-loaded images, due to problems with retrieving image size and source in some mobile browsers. You may add IMG elements dynamically, or switch
href
attribute ofa.rsImg
before the initialization. - If you remove
rsImg
class - slider won't be able to preload or scale the image via JS, use CSS to apply scaling, as shown in http://codepen.io/dimsemenov/pen/jhsJL