Last active
December 23, 2024 05:11
-
-
Save audrasjb/ae2cd8a4306ed8fa69c95742c6f9029b to your computer and use it in GitHub Desktop.
Contextual body classes to help identify browsers and devices types within WordPress front-end
This file contains hidden or 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 | |
/** | |
* Adds <body> custom classes relative to browsers and device types. | |
* | |
* Note: These classes are obtained via WordPress Core Globals and via the wp_is_mobile | |
* function which both rely on the user agent. wp_is_mobile() is obviously NOT a substitute | |
* to CSS media queries, but may be used for device specific features or debugging. | |
* | |
* @see https://developer.wordpress.org/apis/global-variables/#browser-detection-booleans | |
* @see https://developer.wordpress.org/reference/functions/wp_is_mobile/ | |
*/ | |
function who_user_agent_body_classes( $classes ) { | |
$user_agent_classes = array( | |
// Browsers related classes. | |
'is-chrome' => $GLOBALS['is_chrome'], | |
'is-safari' => $GLOBALS['is_safari'], | |
'is-gecko' => $GLOBALS['is_gecko'], | |
'is-ns4' => $GLOBALS['is_NS4'], | |
'is-opera' => $GLOBALS['is_opera'], | |
'is-ie' => $GLOBALS['is_IE'], | |
'is-edge' => $GLOBALS['is_edge'], | |
'is-lynx' => $GLOBALS['is_lynx'], | |
// Devices related classes. | |
'is-iphone' => $GLOBALS['is_iphone'], | |
'is-mobile' => wp_is_mobile(), | |
'is-desktop' => ! wp_is_mobile(), | |
); | |
foreach ( $user_agent_classes as $class => $is_matching ) { | |
if ( $is_matching ) $classes[ $class ] = $class; | |
} | |
return $classes; | |
} | |
add_filter( 'body_class', 'who_user_agent_body_classes' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment