To add a custom body class using the wp_is_mobile
function in WordPress, you can use the body_class
filter hook in your theme’s functions.php
file. This hook allows you to modify the body classes that are applied to the <body>
element of your site’s pages.
Here’s an example of how you can use this hook to add a custom body class based on whether the site is being viewed on a mobile device:
// How to add custom body_class using wp_is_mobile
// More snippets at wpunplugged.com
add_filter( 'body_class', 'add_mobile_body_class' );
function add_mobile_body_class( $classes ) {
if ( wp_is_mobile() ) {
// Add a custom body class for mobile devices
$classes[] = 'mobile-device';
}
return $classes;
}
This code will add the mobile-device
class to the body of any pages that are being viewed on a mobile device. You can then use this class in your theme’s CSS to apply specific styles or behaviors to mobile devices.
Keep in mind that the wp_is_mobile
function may not always accurately detect mobile devices, depending on the capabilities and configurations of different devices. If you need a more robust solution for detecting mobile devices, you may want to consider using a plugin or a custom function that uses a different method for detecting mobile devices.