WordPress Mobile Specific Content

Often you will come to situation where you want to show specific content in a different way for mobile and desktop users. Sure you can use some CSS trickery of displaying or hiding some portion of the content but the fact is that hiding is not the same as not loading at all. It will affect the speed and on mobile devices issue of page loading speed is even more important than on the desktop.

Here is example of how to load a different shortcode for mobile and non-mobile visitors. Fortunately this mobile detector works just fine. Add this to functions.php file like it says in the comments.

// Add to functions.php
// version proof, checks if the visitor is from a mobile device
function muneeb_wp_is_mobile() {

    if ( function_exists( 'wp_is_mobile' ) )
        return wp_is_mobile();

    //code from wp_is_mobile function, wp_is_mobile() is located in wp-includes/vars.php version 3.4
    static $is_mobile;

    if ( isset($is_mobile) )
        return $is_mobile;

    if ( empty($_SERVER['HTTP_USER_AGENT']) ) {
        $is_mobile = false;
    } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false // many mobile devices (all iPhone, iPad, etc.)
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false ) {
            $is_mobile = true;
    } else {
        $is_mobile = false;
    }

    return $is_mobile;
}

 
Now you are ready to do the trick. In your template (page) file you can now call the optional shortcodes for mobile and non mobile devices.

 

if ( muneeb_wp_is_mobile() ): echo do_shortcode('[shortcode1]'); else: echo do_shortcode('[shortcode2]'); endif 

So basically what it does it executes ‘shortcode1’ if the device is mobile and the ‘shortcode2’ if its not. Of course you need to wrap this in PHP tag. For instance you could show one slider for desktop and the other slider for mobile visitors without loading the content that is not required. Normally this will have effect on your web page loading speed.