• Resolved ursego

    (@ursego)


    How to hide/show a text fragment in a widget depending on the device (mobile / large screen)?

    In PHP files, the following condition works:

    <?php if ( wp_is_mobile() ) { ?>
    ...
    <?php } ?>

    But it desn’t work in a WIDGET, placed on a side bar…
    The style is Mantra.

Viewing 7 replies - 1 through 7 (of 7 total)
  • anonymized-13749270

    (@anonymized-13749270)

    Text widgets are for plain text and HTML markup only..

    You could create a shortcode, adding this to your child theme’s functions file:

    function my_mobile_widget( $atts ) {
    
    	$a = shortcode_atts( array(
            'content' => ''
        ), $atts );
    
    	ob_start();
    
    	if ( wp_is_mobile() ) // when using a mobile browser, echo the content
    		echo "{$a['content']}";
    
    	return ob_get_clean();
    }
    add_shortcode( 'my-mobile-widget', 'my_mobile_widget' );
    // if your text widgets don't output shortcodes contents
    add_filter('widget_text', 'do_shortcode');

    Now put this test shortcode in a new text widget:

    [my-mobile-widget content="<p><b>Hello</b> there! Thanks for <i>visiting!!</i></p>"]

    Update content attribute to what you need, and let us know how it goes

    Thread Starter ursego

    (@ursego)

    How to write the following logic (i use pseudo-code):

    IF mobile device THEN
       one fragment
    ELSE
       another fragment
    END IF

    ?

    anonymized-13749270

    (@anonymized-13749270)

    Just add an else right after the wp_is_mobile condition, like:

    if ( wp_is_mobile() ) // when using a mobile browser, echo the content
    	echo "{$a['content']}";
    else // when in desktop
    	echo "something else, not in mobile";

    Watch out for syntax errors.

    You can also set additional attributes for desktop:

    function my_mobile_widget( $atts ) {
    
    	$a = shortcode_atts( array(
            'mobile' => '',
            'desktop' => ''
        ), $atts );
    
    	ob_start();
    
    	if ( wp_is_mobile() ) // when using a mobile browser, echo the content
    		echo "{$a['mobile']}";
    	else
    		echo "{$a['desktop']}";
    
    	return ob_get_clean();
    }
    add_shortcode( 'my-mobile-widget', 'my_mobile_widget' );

    [my-mobile-widget mobile="<p>You are browsing this site on mobile</p>" desktop="<p>You are browsing this site on dekstop</p>"]

    Thread Starter ursego

    (@ursego)

    Thanks!!!

    anonymized-13749270

    (@anonymized-13749270)

    Hope it worked for you, you are welcome 🙂 !

    Thread Starter ursego

    (@ursego)

    Just tested – it works!!! Lots of thanx!!!

    anonymized-13749270

    (@anonymized-13749270)

    Awesome!! Glad to hear it worked for you!

    Mark as resolved, and have a nice day 🙂

Viewing 7 replies - 1 through 7 (of 7 total)

The topic ‘Define mobile device in a widget’ is closed to new replies.