Enable different image url based on window size, adaptive images

greene.md's Avatar

greene.md

30 May, 2013 03:15 AM

Can I enable the plugin to use the different sizes of images Wordpress creates based on my media settings depending on the size of the users browser? This could save many kb for mobile/tablet users. Grabbing inspiration from http://adaptive-images.com/

Awesome plugin!

  1. Support Staff 1 Posted by Dmitry Semenov on 30 May, 2013 07:30 PM

    Dmitry Semenov's Avatar

    Hi,

    Implementing of this feature requires a bit of JS coding knowledge, if you know it - let me know and I'll provide more details.. I'm planning to add it to WP version in future updates.

    Dmitry

  2. 2 Posted by greene.md on 31 May, 2013 12:22 PM

    greene.md's Avatar

    Dmitry, I've written a fair bit of JavaScript mostly based of jQuery. Do you already have code written or are you asking if I've tried to create the functionality myself? Thanks,

  3. Support Staff 3 Posted by Dmitry Semenov on 01 Jun, 2013 07:33 PM

    Dmitry Semenov's Avatar

    No, I'm just asking if you know JS or not. If you're using WP version:

    1) First of you need to create custom {{variable}} that will return URL of smaller version of the images. http://help.dimsemenov.com/kb/wordpress-royalslider-advanced/wp-add...

    2) Then go to slide markup editor and add this variable to image tag as an attribute, e.g. replace {{image_tag}} with this:

    <a href="{{image_url}}" class="rsImg" data-small-image="{{name_of_variable_that_you_created}}">{{title}}</a>
    

    3) Lastly, just add JavaScript that will replace the URL if the screen size is small, e.g.:

    if($(window).width() < 600) {
        $('.rsImg').each(function() {
           $(this).attr('href', $(this).data('small-image'));
       });
    }
    

    Just make sure that you added before slider initialization (before footer).

    That's all.

    Dmitry

  4. 4 Posted by greene.md on 05 Jun, 2013 11:59 PM

    greene.md's Avatar

    Thanks Dmitry, here's the code I've got working in case anyone else is interested.

    Wordpress theme functions.php file

    if ( function_exists( 'add_theme_support' ) ) {
        add_theme_support( 'post-thumbnails' );
        add_image_size( 'billboard_full', 1680, 622 );
        add_image_size( 'billboard_large', 1280, 474 );
        add_image_size( 'billboard_tablet', 851, 315 );
        add_image_size( 'billboard_mobile', 719, 266 );
    }
    
    /**
     * Extends the Royal Slider plugin for adaptive images
     * based on screen size to increase performance
     *
     * @since Awaken Benehime V11
     *
     * @param array post
     * @param array options
     * @return variable
     */
    
    // Create PHP class that will hold methods
    class MyRoyalSliderRendererHelper {
        private $post;
        private $options;
        private $thumbnail;
        function __construct( $data, $options ) {
            // $data variable holds WordPress post object only for Posts Slider
            // for other types sliders it holds just data associated with slide, print it to see what's inside
            $this->post = $data;
            // slider options (that you choose in right sidebar)
            $this->options = $options;
        }
        
        function billboard_full() {
            $this->thumbnail = wp_get_attachment_image_src( $this->post['image']['attachment_id'], 'billboard_full' );
          return $this->thumbnail[0];
        }
        function billboard_large() {
            $this->thumbnail = wp_get_attachment_image_src( $this->post['image']['attachment_id'], 'billboard_large' );
          return $this->thumbnail[0];
        }
        function billboard_tablet() {
            $this->thumbnail = wp_get_attachment_image_src( $this->post['image']['attachment_id'], 'billboard_tablet' );
          return $this->thumbnail[0];
        }
        function billboard_mobile() {
            $this->thumbnail = wp_get_attachment_image_src( $this->post['image']['attachment_id'], 'billboard_mobile' );
          return $this->thumbnail[0];
        }
        function post_id() {
           // return var_dump($this->post);
        }
    }
    
    /**
     * @param  [object] $m       Mustache_Engine object 
     * @param  [object] $data    Object with slide data (for example for posts slider it's WordPress Post Object)
     * @param  [object] $options Array of RoyalSlider options
     */
    function newrs_add_custom_variables($m, $data, $options) {
    
        // initialize helper class
        $helper = new MyRoyalSliderRendererHelper($data, $options);
    
        // add {{hello_world}} variable that gets data from hello_world function of MyRoyalSliderRendererHelper class
        $m->addHelper('billboard_full', array($helper, 'billboard_full') );
        $m->addHelper('billboard_large', array($helper, 'billboard_large') );
        $m->addHelper('billboard_tablet', array($helper, 'billboard_tablet') );
        $m->addHelper('billboard_mobile', array($helper, 'billboard_mobile') );
    
        // same, but for post_id
        $m->addHelper('post_id', array($helper, 'post_id') );
    }
    add_filter('new_rs_slides_renderer_helper', 'newrs_add_custom_variables', 10, 4);
    

    Javascript file

    $(function() {
        if($(window).width() < 720) {
            $('.rsImg').each(function() {
                $(this).attr('href', $(this).data('image-mobile'));
            });
        }
        else if($(window).width() < 852) {
            $('.rsImg').each(function() {
                $(this).attr('href', $(this).data('image-tablet'));
            });
        }
        else if($(window).width() < 1367) {
            $('.rsImg').each(function() {
                $(this).attr('href', $(this).data('image-large'));
            });
        }
        else if($(window).width() >= 1367) {
            $('.rsImg').each(function() {
                $(this).attr('href', $(this).data('image-full'));
            });
        }
    });
    

    RoyalSlider slide markup

    <div class="rsContent">
      <a href="{{image_url}}" class="rsImg" 
         data-image-mobile="{{billboard_mobile}}"
         data-image-tablet="{{billboard_tablet}}"
         data-image-large="{{billboard_large}}"
         data-image-full="{{billboard_full}}"
             >{{title}}</a>
      {{thumbnail}}
      {{html}}
      {{animated_blocks}}
      {{#link_url}}
      <a class="rsLink" href="{{link_url}}">{{title}}</a>
      {{/link_url}}
    </div>
    
  5. Support Staff 5 Posted by Dmitry Semenov on 06 Jun, 2013 11:19 AM

    Dmitry Semenov's Avatar

    Thank you for sharing, I'm sure it'll helpful to someone.

    Dmitry

  6. 6 Posted by arne on 14 Jun, 2013 06:33 PM

    arne's Avatar

    thanx a lot for sharing this

    Arne

  7. 7 Posted by Marcus on 08 Aug, 2014 10:47 PM

    Marcus's Avatar

    I'm trying to do this to a non-WP site, and it doesn't seem to replace the images, I put the JS before initializing, and the images still load full size on mobile.

    Here is my code - please let me know what I'm doing wrong. Thanks!

    HTML:
    <img class="rsImg" src="normal-image.jpg" alt="" data-small-image="small-image.jpg" />

    Javascript at bottom of page:

    jQuery(window).bind("load", function() {
    jQuery(function($) { 
        if( $(window).width() < 400 ){
            $('.rsImg').each(function() {
               $(this).attr('href', $(this).data('small-image'));
           });  
        }
        
          $(".royalSlider").royalSlider({
            keyboardNavEnabled: true,
            autoScaleSlider: true,
            autoScaleSliderWidth: 825,
            autoScaleSliderHeight: 370,
            arrowsNav: false,
            imageScaleMode: 'fill',
            loop: true,
            globalCaption:true,
            autoPlay: {
                enabled: true,
                pauseOnHover: true,
                delay: 3500
            }
        });  
    });
    });
    
  8. Support Staff 8 Posted by Dmitry Semenov on 09 Aug, 2014 05:38 PM

    Dmitry Semenov's Avatar

    @Marcus, your code is correct at first glance, are you sure that you resized window to less than 400px? Please link to page that you're working on.

    Dmitry

  9. 9 Posted by Marcus on 11 Aug, 2014 03:10 PM

    Marcus's Avatar

    Dmitry,
    Yes, I've changed my replacement statement so that the small images are completely different and added a console.log to see that the href is definitely being changed, it's just not picked up by RS:

    if( $(window).width() < 400 ){
            $('.rsImg').each(function() {
               //$(this).attr('href', $(this).data('small-image'));
               $(this).attr('href', 'http://placehold.it/330x148/');
               console.log($(this).attr('href'));
           });
    }

    The site is actually a WP site, but it's using the standard JS implementation of your script. - http://purnellenergy.com

  10. Support Staff 10 Posted by Dmitry Semenov on 11 Aug, 2014 06:17 PM

    Dmitry Semenov's Avatar

    Oh, you're using img.rsImg, not a.rsImg http://dimsemenov.com/plugins/royal-slider/documentation/#images , that's why you should modify src attribute, not href.

    Dmitry

  11. 11 Posted by Marcus on 11 Aug, 2014 06:38 PM

    Marcus's Avatar

    Of course! That was quite stupid of me. Thanks for sorting that out - works great now!

  12. Support Staff 12 Posted by Dmitry Semenov on 11 Aug, 2014 06:49 PM

    Dmitry Semenov's Avatar

    btw, I recommend switching to <a class="rsImg" href="image.jpg">alt text</a> markup, as with your current HTML code, you'll load both - normal-image and small-image. Or at least make small-image, default one.

    Dmitry

  13. 13 Posted by Marcus on 11 Aug, 2014 07:07 PM

    Marcus's Avatar

    @Dmitry - thanks I will do that as well.

  14. 14 Posted by tracy on 14 Oct, 2014 05:05 PM

    tracy's Avatar

    Thanks green.md and Dmitry for sharing this. However I'm having trouble implementing it. The html isn't reflecting the mustache helpers.

    Here is the functions.php code:

    // Create PHP class that will hold methods
    class MyRoyalSliderRendererHelper {
        private $post;
        private $options;
        private $thumbnail;
        function __construct( $data, $options ) {
            // $data variable holds WordPress post object only for Posts Slider
            // for other types sliders it holds just data associated with slide, print it to see what's inside
            $this->post = $data;
            // slider options (that you choose in right sidebar)
            $this->options = $options;
        }
    
        function fslider_large() {
        $this->thumbnail = wp_get_attachment_image_src( $this->post['image']['attachment_id'], 'fslider_large' );
        return $this->thumbnail[0];
        }
        function fslider_medium() {
            $this->thumbnail = wp_get_attachment_image_src( $this->post['image']['attachment_id'], 'fslider_medium' );
            return $this->thumbnail[0];
        }
        function fslider_small() {
            $this->thumbnail = wp_get_attachment_image_src( $this->post['image']['attachment_id'], 'fslider_small' );
            return $this->thumbnail[0];
        }
        function post_id() {
           //return $this->post->ID;
        }
    }
    
    /**
     * @param  [object] $m Mustache_Engine object
     * @param  [object] $data Object with slide data (for example for posts slider it's WordPress Post Object)
     * @param  [object] $options Array of RoyalSlider options
     */
    function fc_add_custom_rs_variables($m, $data, $options) {
    
        // initialize helper class
        $helper = new MyRoyalSliderRendererHelper($data, $options);
    
        // add {{fslider_xsize}} variable that gets data from flair_xsize function of MyRoyalSliderRendererHelper class
        $m->addHelper('fslider_large', array($helper, 'fslider_large') );
        $m->addHelper('fslider_medium', array($helper, 'fslider_medium') );
        $m->addHelper('fslider_small', array($helper, 'fslider_small') );
    
        // same, but for post_id
        $m->addHelper('post_id', array($helper, 'post_id') );
    
    }
    add_filter('new_rs_slides_renderer_helper', 'fc_add_custom_rs_variables', 10, 4);
    

    The Royalslider slide markup:

    <div class="rsContent">
      <a href="{{image_url}}" class="rsImg" 
         data-image-small="{{fslider_small}}"
         data-image-medium="{{fslider_medium}}"
         data-image-large="{{fslider_large}}"
         data-image-full="{{fslider_large}}"
             >{{title}}</a>
      <div class="rsCaption">
        {{description}}
        </div>
      <div class="rsTmb">
        <span class="pointer"></span>
        <h5>{{title}}</h5>
        </div>
      {{html}}
      {{#link_url}}
      <a class="rsLink" href="{{link_url}}">{{title}}</a>
      {{/link_url}}
    </div>
    

    And the html output (truncated):

    <a href="http://flaircleaners.dev/wp-content/uploads/slider_flair_cleaners_vip_express1.jpg" class="rsImg" 
         data-image-small="Array"
         data-image-medium="Array"
         data-image-large="Array"
         data-image-full="Array"
             >VIP Express</a>
    ...
    

    Thanks

  15. Support Staff 15 Posted by Dmitry Semenov on 14 Oct, 2014 07:27 PM

    Dmitry Semenov's Avatar

    @Tracy, just debug it, does it work if you do this:

    function fslider_large() {
    
        return 'test';
     }
    

    ? Does it work with post_id variable from initial example?

  16. 16 Posted by tracy on 14 Oct, 2014 08:43 PM

    tracy's Avatar

    @Dmitry Thanks for getting back so quick. Of course, dumb user error. I realized it's not a Posts slider, thus this method won't work.

  17. 17 Posted by tracy on 15 Oct, 2014 12:20 AM

    tracy's Avatar

    Would someone be able to point me in the right direction for using this method with a custom slider as opposed to a post slider? I'm unsure how to pull the image attachment data on non-post slides.

  18. Support Staff 18 Posted by Dmitry Semenov on 15 Oct, 2014 08:14 AM

    Dmitry Semenov's Avatar

    @Tracy, there is example at the end of this thread - http://help.dimsemenov.com/discussions/royalslider-wordpress/27529-...

  19. 19 Posted by ritchie.davies on 07 Jun, 2015 10:33 AM

    ritchie.davies's Avatar

    In reference to the post at:
    Posted by greene.md on Jun 06, 2013 @ 12:59 AM

    I get the overall principle, however, I should be most grateful for a few extra pointers in setting this up from the start. Firstly, I understand where to write the RoyalSlider slide markup, under the particular slider's edit options for the plug-in, in the Wordpress Dashboard area. The main questions that I have are:

    1. Is the "Javascript File" written inside the functions.php file or at the beginning of the header.php file for my site?

    2. How to I add the images of different size versions and what is the best naming convention? . For example, If I create a series of suitably-sized, source images (prior to uploading) of flower_full.jpg, flower_large.jpg, flower_tablet.jpg and flower_moble.jpg as well as similarly named photos of tree_full. jpg, tree_large.jpg etc. and so on. Do I upload them to the same site-based content folder? Do I add all the different size version to the slider using the add images button, under the slider edit window, so that they are available for Royal Slider to load depending on the browsing device in use?

    Thanks for your help

  20. Support Staff 20 Posted by Dmitry Semenov on 07 Jun, 2015 05:27 PM

    Dmitry Semenov's Avatar

    @ritchie.davies,

    1. Is the "Javascript File" written inside the functions.php file or at the beginning of the header.php file for my site?

    JS code can be added to any .js file before the slider init code (slider init code is in footer). E.g. in your theme main.js file, or custom one https://codex.wordpress.org/Function_Reference/wp_enqueue_script

    Please note that above modification requires at least basic knowledge, if you're not experienced – consider hiring a developer.

    How to I add the images of different size versions and what is the best naming convention? . For example, If I ...

    Above code by greene.md uses WordPress media library and automatically resize images. You need to upload just one size to WordPress.

Reply to this discussion

Internal reply

Formatting help / Preview (switch to plain text) No formatting (switch to Markdown)

Attaching KB article:

»

Attached Files

You can attach files up to 10MB

If you don't have an account yet, we need to confirm you're human and not a machine trying to post spam.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac