Post Pic

How to detect the visitor browser within WordPress

To ensure maximum cross-browser compatibility on your blog theme, you have to be able to detect the browser used by the visitor. Sure, you can use conditionnal comments, but WordPress itself can detect client browser. Let’s see how to do.

Simply paste the code below in your functions.php file:

<?php
add_filter('body_class','browser_body_class');
function 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';
	else $classes[] = 'unknown';

	if($is_iphone) $classes[] = 'iphone';
	return $classes;
}
?>

Once you saved the file, the function will automatically add a CSS class to the body tag, as shown in the exemple below:

<body class="home blog logged-in safari">

That's all. You just have to take your stylesheet, and add some browser-specific styles!

Credits goes to Nathan Rice for this awesome trick!

Related Posts

Related Posts

No related posts.

3 Responses

Jul 19 2011 19:55

This is a great tip. I wasn’t aware that WP had the is_XX to check for browsers. Thanks.

Aug 01 2012 10:15

simple and easy tip but with great results.
Thanks for this one!

Jan 11 2013 03:06

This can detect any mobile device?

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox