X

How to add browser and Operating System Classes to WordPress Body Class

Snippets by IsItWP

Wondering how to add user’s browser and Operating System classes to WordPress body class? When developing WordPress themes, you may need browser and OS information of your users so you can dynamically modify certain aspects of your design with CSS or jQuery.

The below snippets will add class based on the users operating system and browser.

Instructions:

Step 1: Add this snippet to the functions.php file or in a site-specific plugin

	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');

Step 2: Add this snippet within the body tag of your wordpress header.php template. <body <? body_class(); ?>>

<?php body_class(); ?>

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 62 best free WordPress blog themes or 7 best WordPress contact form plugins.

Comments  Leave a Reply

  1. Thanx for this snippet, but is possible to also identify the windows version?, like XP, Win 7 and Win 8?

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!