Skip to content

Instantly share code, notes, and snippets.

@ihorvorotnov
Last active August 28, 2022 11:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ihorvorotnov/9c9c4b0b68cff90b36ae to your computer and use it in GitHub Desktop.
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)
jQuery( document ).ready( function($) {
if ( $( "body" ).hasClass("wp-is-mobile"){
/* Do javascript for mobile */
}
else{
/* Do javascript for non-mobile */
}
});
<?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;
}
?>
@ihorvorotnov
Copy link
Author

Be aware this technique won't help if you use full page caching.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment