How to add custom body_class using wp_is_mobile in WordPress

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.

Share this post

You might also like...

Sucuri for WordPress Review
Plugins

Sucuri for WordPress Review

Sucuri for WordPress is a powerful security plugin that helps protect your website from hackers and malicious software. It provides a comprehensive website security solution,

Read More »

Comment

Your email address will not be published. Required fields are marked *