Updated Add the User’s Browser Name to WordPress’ Body Class

This has been floating around forever but there are a few issues with it in today’s responsive / mobile device world. Basically, this type of code checks against some variables WordPress sets depending on the user’s browser and then adds a new class to the <body> tag. However, it’ll set the same body class for iPhone as it does for normal Safari on your desktop (It also rarely includes Android in the mix). Though they share a similar name, the two versions of Safari can differ quite a bit.

Let’s look at our new code. We’ll dissect it momentarily:

// add browser name to body class

function browser_body_class($classes) {
global $is_gecko, $is_IE, $is_opera, $is_safari, $is_chrome, $is_iphone;
if(!wp_is_mobile()) {
if($is_gecko) $classes[] = 'browser-gecko';
elseif($is_opera) $classes[] = 'browser-opera';
elseif($is_safari) $classes[] = 'browser-safari';
elseif($is_chrome) $classes[] = 'browser-chrome';
elseif($is_IE) $classes[] = 'browser-ie';
else $classes[] = 'browser-unknown';
} else {
if($is_iphone) $classes[] = 'browser-ios';
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false) $classes[] = 'browser-android';
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false) $classes[] = 'browser-kindle';
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false) $classes[] = 'browser-blackberry';
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false) $classes[] = 'browser-opera-mini';
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false) $classes[] = 'browser-opera-mobi';
return $classes;

Tomorrow I’ll show you how to get even more detailed with this, so we can pick apart iPad, Android tablets, etc.

For today’s code though, essentially what we do is load up some variables WordPress stores based on the visitor’s user agent. Then we check, via the somewhat generic WordPress function wp_is_mobile(), whether they’re using a mobile device or not. If they aren’t, we add a browser class based on the browser they’re using.

If they are, we do the same, but we break them apart like this in order to avoid getting the same classes for mobile and desktop versions of Safari. Enjoy!

Up Next: How to Make an Avatar Icon using Nothing but CSS & HTML