Last active
August 28, 2022 11:08
-
-
Save ihorvorotnov/9c9c4b0b68cff90b36ae to your computer and use it in GitHub Desktop.
Using wp_is_mobile() in WordPress to detect mobile users (phones and tablets)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery( document ).ready( function($) { | |
if ( $( "body" ).hasClass("wp-is-mobile"){ | |
/* Do javascript for mobile */ | |
} | |
else{ | |
/* Do javascript for non-mobile */ | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if ( wp_is_mobile() ) : | |
/* do stuff for mobile user */ | |
else : | |
/* do stuff for non mobile user */ | |
endif; | |
/* Filter body class */ | |
add_filter('body_class','my_theme_body_class'); | |
/** | |
* Add Mobile Body Class "wp-is-mobile" for mobile and "wp-is-not-mobile" for non-mobile device | |
*/ | |
function my_theme_body_class( $classes ){ | |
if ( wp_is_mobile() ) : | |
$classes[] = 'wp-is-mobile'; | |
else : | |
$classes[] = 'wp-is-not-mobile'; | |
endif; | |
return $classes; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Be aware this technique won't help if you use full page caching.