Did you know that WordPress has a mobile detect function already? In this post, I will show you how you can use wp_is_mobile function to create a simple shortcode to hide certain parts of your posts from mobile visitors or the other way.


Demonstration

Desktop View

mobile-shortcode-desktop-view

Mobile View

mobile-shortcode-mobile-view


The Shortcode

wp_is_mobile function returns true when your site is viewed from a mobile browser. Using this simple function you can create awesome responsive WordPress themes. Here we will use it to check if we should return content between shortcodes or not.

To use the shortcodes [desktoponly] and [mobileonly] just add following code to your functions.php file:

<?php 

// [desktoponly] shortcode
add_shortcode('desktoponly', 'shailan_desktop_only_shortcode');
function shailan_desktop_only_shortcode($atts, $content = null){ 
    if( !wp_is_mobile() ){ 
        return wpautop( do_shortcode( $content ) ); 
    } else {
        return null; 
    } 
}
 
// [mobileonly] shortcode
add_shortcode('mobileonly', 'shailan_mobile_only_shortcode');
function shailan_mobile_only_shortcode($atts, $content = null){ 
    if( wp_is_mobile() ){ 
        return  wpautop( do_shortcode( $content ) ); 
    } else {
        return null; 
    } 
}

?>

This code will add required shortcode functions to your theme.


Usage

After you add the shortcode functions.php wrap your content using either [desktoponly][/desktoponly] or [mobileonly][/mobileonly] tags as required:

After you add the shortcode tags as necessary, all you need is to publish. The content inside [desktoponly][/desktoponly] will be visible to desktop/laptop users only. And the text inside [mobileonly][/mobileonly] tags will be visible to phone users only.

For more WordPress tips & tricks, be sure to follow us on facebook or twitter.