I am finding a way to add A before the menu if we are on desktop and to add B if we are on mobile device.

As such, this is are my functions for A and B:

add_action( 'wp_head', 'A_function' );
function A_function() {
    //add A
add_filter( 'wp_nav_menu_items', 'B_function', 10, 2 );
function B_function() {
    //add B

I know I need to put these hooks in functions file but I don't know the way to do it, I know we can use wp_is_mobile().

How can I achieve that?


According to codex, wp_is_mobile(); is a boolean function that returns true if the user is visiting the website on a mobile device, so what you need is:

if ( wp_is_mobile() ) {
    // Run this only for mobile visitors
    add_filter( 'wp_nav_menu_items', 'B_function', 10, 2 ); function B_function(/* add B */ );
} else {
    //If we are not on mobile, then run this filter
    add_action( 'wp_head', 'A_function' ); function A_function(/* add A */);
  • very bad idea, is not realiable, breaks caching, not responsive, and probably have more bad attributes – Mark Kaplun Jun 5 '17 at 9:32
  • @MarkKaplun Well i can't think of any other server-side method to do this, and i don't think we will be able to do this by AJAX since the filters are already applied after page load? Gotta choose between worse and worst ( Bad doesn't apply here ) – Jack Johansson Jun 5 '17 at 9:36

WP's PHP code runs server–side — it is not and cannot be aware of screen of the client device.

wp_is_mobile() relies on user agent sniffing, that is tries to match data that client’s browser provides. The technique is considered notoriously unreliable and of very limited use.

Since you don’t provide context on what purpose your links serve, it is hard to advise on fitting approach. Client–side techniques, such as CSS media queries, are commonly used for reliable detection of context in client browser.


wp_is_mobile() should never be used. At this point in time its existence mostly relates to some browser bugs that needs to be handled on admin side.

For anything that needs to be aware of physical device size, or browser window size, it should be done with media rules in CSS and JavaScript.

  • I think the problem is that the OP is trying to add HTML content depending on the user agent, which would render CSS obsolete. I could only think of outputting the entire code to a JavaScript file and handling the issue there. – Jack Johansson Jun 5 '17 at 9:42
  • the proper way to do it is just to always add it and disable its display when not needed. There is really no other way... at least not if you want to be responsive – Mark Kaplun Jun 5 '17 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.