Add browser classes to body using filters in WordPress

Wordpres adds custom classes to <body> depending on the page you are viewing. This is a great function that can be used for styling your theme. Here i will show you how to add body classes depending on the browser your visitor is using. So you can style your theme layout using those classes.

Step1. Open functions.php in your theme root folder.

Step2. Add following block of code somewhere appropriate before ?> at the end of the file – if one exists.

function browser_classes ( $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';
	else $classes[] = 'unknown';
	
	if($is_iphone) $classes[] = 'iphone';
	
	return $classes;
}

add_filter( 'body_class', 'browser_classes' );

Step3. Save & upload the file to your server.

This filter will automatically add browser class to your theme. For example if your visitor visits your site using an iphone, then body class will be:

<body class="... iphone ...">

You can then use this in your stylesheet like this:

 body.iphone #page{ width: 320px; } 

This is usefull for small layout fixes, however if you want to display different content depending on browser, I recommend using WPtouch plugin which simplifies your site for the mobile visitors.

Related Posts

NS Weight Release

WP-Backgrounds Lite by InoPlugs Web Design and Juwelier Schönmann 1010 Wien