When developing WordPress themes, sometimes you may need user’s browser and operating system information to modify certain aspects of your design using CSS or jQuery. WordPress is capable of doing that for you. In this article, we will show you how to add user’s browser and OS classes in WordPress body class.
By default WordPress generates CSS classes for different sections of your website. It also provides filters, so that theme and plugin developers can hook their own classes. You will be using the body_class filter to add browser and operating system information as CSS class.
First thing you need to do is add the following code in your theme’s functions.php file.
function mv_browser_body_class($classes) {
global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;
if($is_lynx) $classes[] = ‘lynx’;
elseif($is_gecko) $classes[] = ‘gecko’;
elseif($is_opera) $classes[] = ‘opera’;
elseif($is_NS4) $classes[] = ‘ns4’;
elseif($is_safari) $classes[] = ‘safari’;
elseif($is_chrome) $classes[] = ‘chrome’;
elseif($is_IE) {
$classes[] = ‘ie’;
if(preg_match(‘/MSIE ([0-9]+)([a-zA-Z0-9.]+)/’, $_SERVER[‘HTTP_USER_AGENT’], $browser_version))
$classes[] = ‘ie’.$browser_version[1];
} else $classes[] = ‘unknown’;
if($is_iphone) $classes[] = ‘iphone’;
if ( stristr( $_SERVER[‘HTTP_USER_AGENT’],”mac”) ) {
$classes[] = ‘osx’;
} elseif ( stristr( $_SERVER[‘HTTP_USER_AGENT’],”linux”) ) {
$classes[] = ‘linux’;
} elseif ( stristr( $_SERVER[‘HTTP_USER_AGENT’],”windows”) ) {
$classes[] = ‘windows’;
}
return $classes;
}
add_filter(‘body_class’,’mv_browser_body_class’);
The first part of this script detects user’s browser and adds it to $classes. The second part detects user’s operating system and adds it to $classes as well. The last line uses the WordPress body_class filter to add classes.
Now you need to add the body class to the HTML tag in your theme’s header.php file. Replace the body line in your template file with this code: