Define mobile device in a widget
-
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.
-
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
How to write the following logic (i use pseudo-code):
IF mobile device THEN one fragment ELSE another fragment END IF?
Just add an
elseright 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>"]Thanks!!!
Hope it worked for you, you are welcome 🙂 !
Just tested – it works!!! Lots of thanx!!!
Awesome!! Glad to hear it worked for you!
Mark as resolved, and have a nice day 🙂
The topic ‘Define mobile device in a widget’ is closed to new replies.