Run shortcode at certain resolution

I’ve gone a roundabout way of trying to ask a question about this here: Loading shortcode with ajax but figured it might be worth asking the fundamental question of what I am trying to do without adding my confused, naive problem-solving into the mix.

I want to run this:

Read More
<?php echo do_shortcode('[metaslider id="8302"]'); ?>

But only if the window size is greater than, for example, 800px.

Any ideas would be much appreciated!

Related posts

3 comments

  1. Ok, let’s clarify the concept.
    You don’t want download the content for mobile device, and you want to rely on screen resolution. You know that php (wordpress) run on server, screen resolution is a completely client-side matter.

    So the flow will be:

    1. user send a request to your site
    2. your site page load on client
    3. some js run on the client, recognize the resolution and in some condition run ajax to send a request to server and load the shortcode

    What’s wrong here? Simple: screen resolution is not enough to know client device. E.g. in this moment I’m writing from a desktop PC with a monitor of 26″, but the browser window is not in full size and probably is low than 800 px. For me the flow below will not load shortcode. Is this what you want? I don’t think so.

    Maybe you can rely on a window.resize js event so when I change my window size to be more than 800 px you load the shortcode otherwise you remove the shortcode.
    In this case an ajax request is sended to server when a client resize window in a way that it exceeds the breakout resolution:

    jQuery().ready( function($) {
    
    function load_shortcode() {
       if ( $(window).innerWidth() > 800 ) {
          if ( $('#slider .slider-content').length && ! $('#slider').is(':visible') ) {
            // slider was loaded but is hidden, show it
            $('#slider').show();
          } else {
            // slider never loaded, load it
            $.ajax({
              url: myscriptvars.ajaxurl,
              data: { action: 'load_slider_shortcode' }
            }).done(function(output){
              if (output) $('#slider').html(output);
            });
          }
        } else {
           // slider is there but window was resized in less than 800px: hide it
           if ( $('#slider .slider-content').length) $('#slider').hide();
        }
    }
    
    $(window).resize(function() {
       load_shortcode();
    });
    
    load_shortcode();
    
    });
    

    Is this what you want? Maybe, but there is another solution (a better solution in my opinion).

    WordPress as a function wp_is_mobile that recognize mobile device, but it return true even if device is a 10″ tablet with hi-res screen. This is not ideal but there is a script than can help you. It’s Mobile Detect.

    How use it: download it and put in a folder. For semplicity I assume it is in your theme root. In your page, where the shortcode have to appear put someting like:

    @include_once( trailingslashit(TEMPLATEPATH) . 'Mobile_Detect.php' );
    $detect = new Mobile_Detect;
    $ismobile = ( $detect->isMobile() && ! $detect->isTablet() ); // true only for phones
    if ( $mobile ) echo do_shortcode('[metaslider id="8302"]');
    

    That’s all. No need ajax, no need rely on window.resize and phone never download your shortcode, PC and tablets download it always.

    If you want to avoid tablets download slider, remove second condition inside if statement.

    To improve solution you can also hide slider on low resolution via css media queries, so desktops and tablets with resized window (like the mine, now) don’t view the slider.

    Not perfect, sure, but at this time I think there is not perfect solution for that matter and this last one seems to me the best among the possibilities.

  2. You’ll need some JavaScript on the front end to measure the users screen size.
    Then you can set a cookie which sends that information with every request.

    Pseudo code: On page load, get the window size and store that value in a cookie.

    You can use that information in your PHP code to make decisions about whether to run certain code or not.

    if( $_COOKIE['screen-size'] > 800 ) {
      //Whatever!
    }
    

    CSS Tricks as a great article laying out how to make a technique like this work -> http://css-tricks.com/make-client-side-data-available-server-side/

    This won’t work if you are caching with something like WP Super Cache or W3 Total Cache because those plugins cache the output of your template so your server is doing less work with every request. If some dynamic condition changes in the request, the logic that needs to be run through PHP won’t execute.

  3. Alternate Method

    The author of Metaslider suggests using WP Mobile Detect. Here is a sample of code I used to achieve a similar result to what I think you are looking for. Requires the WP Mobile Detect plugin.

    <?php if(shortcode_exists('metaslider') && function_exists(wpmd_is_notphone) && wpmd_is_notphone()):
                echo(do_shortcode('[metaslider id=8302]'));
    endif; ?>
    

    I still use an @media query to hide the slider depending on screen width and I know that this isn’t 100% compatible. But, a good fallback might be to include a single image in the event that the slider doesn’t load. This way there will always be content in the flow of the design where it needs to be.

    Initial Method

    This method does not work specifically for the Metaslider plugin as the author never intended on having the shortcode called via AJAX. You will get something to display, but no functionality. It may be possible to include the JS files and execute the appropriate command to begin the slider, but the alternate method above will be so much easier. This method will, however, still work for some other/similar needs.

    I feel your pain @dontwakemeup. I want to do much the same thing. I like using metaslider and I often use CSS @media for screen width detection rather than actual device detection because I don’t care about the specific device, I care about the screen width and the layout of my content. I want to hide the slider below certain widths, regardless of device because it fits the flow of the design layout.

    Description is below; when it’s all said and done the procedure will go something like this

    1. load page without slider
    2. AJAX check if slider is loaded (via and added class name or your own preferred method) and check screen width to see if a slider is needed. (@gmazzap’s load_shortcode() function may be what you are looking for here)
    3. If needed: load the slider.
    4. Any future AJAX calls will be quickly met with a check to see that the content is already loaded (via step 2) and abruptly end.
    5. Keep a CSS @media query to potentially hide the already loaded slider if the screen width changes. No use trying to ‘unload’ anything only to possibly have to ‘re-load’ it again later.

    Here is some code I found that allows you to call a function once per a chosen time period. This is useful along with an AJAX call to limit how many times the function gets called during a user’s resize . This way the function will ideally get called only once per resize. Rather than being called for every frame that happens while the user is changing the window to fit their desires. (This could be a lot of times, and you only need one… after the user is finished)

    var event_call_function_once = (function ()
    {
    var timers = {};
    return function (callback, ms, uniqueId)
    {
        if (!ms)
        {
            ms = 2000;
        }
        if (!uniqueId)
        {
            uniqueId = "Don't call this twice without a uniqueId";
        }
        if (timers[uniqueId])
        {
            clearTimeout (timers[uniqueId]);
        }
        timers[uniqueId] = setTimeout(callback, ms);
    };
    })();
    

    I found this code on Stack Overflow, HERE, and modified it slightly per my own desires.

    From here you will want to add a loaded class name to the container, or some other way of detecting that the slider shortcode has been loaded via AJAX. This will keep from trying to load things more than once. (Again, I believe @gmazzap’s function can do this for you.)

    You will still want to use CSS @media query to hide the slider depending on screen width to keep the layout in order for users who change their screen width on a desktop (as was mentioned earlier). In my opinion I think @gmazzap’s function goes a bit overboard here by using jQuery to hide the slider when an @media query will work fine.

    NOTE: @gmazzap’s function looks fine, however he does not show the WordPress side of the AJAX call. You will need to build that to suit your needs.

    The WordPress side of you AJAX call could be something as simple as:
    (Just an example, I haven’t tested it. Your mileage will vary.)

    //WP AJAX action function
    function load_slider_shortcode() 
    {               
        echo(do_shortcode('[metaslider id=8302]')); 
        die();
    }
    

    Hope this helps you, or anyone else who finds this page. I know I will be using it myself as needed.

Comments are closed.