Blog

Shortcode for Mobile Content

Recently it was asked if there was an easy way to use a WordPress shortcode to easily hide or show wrapped content on mobile devices.  While there are numerous plugins and even a few themes that offer this functionality out of the box, there can be issues when you change a plugin or theme.  So I put together some basic code that can be placed in either the active theme’s functions.php file or placed in a plugin you may use on your WordPress website.

The two pieces of code below will enable two shortcodes to be used on your WordPress sites:

[hide_from_mobile]Content you want hidden from mobile browsers.[/hide_from_mobile]

&

[show_if_mobile]This content will only show on mobile browsers.[/show_if_mobile]

[edd_restrict id=”279,327,3218″ message=”The additional content, code snippets, and enhanced discussions are only available to members of the WPStudio Community.“]

The two pieces of code are as follows:

<?php
function wps_hide_from_mobile_shortcode( $atts, $content = '' ){
    if ( wp_is_mobile() === true ) {
        $content = '';
    }
    return $content;
}
add_shortcode( 'hide_from_mobile', 'wps_hide_from_mobile_shortcode' );
<?php
function wps_show_if_mobile_shortcode( $atts, $content = '' ){
    if ( ! wp_is_mobile() === true ) {
        $content = '';
    }
    return $content;
}
add_shortcode( 'show_if_mobile', 'wps_show_if_mobile_shortcode' );

[/edd_restrict]
If you have any questions, you can ask them below.

Subscribe for Updates and Special Deals




Marketing permission: I give my consent to to be in touch with me via email using the information I have provided in this form for the purpose of news, updates and marketing.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.