Detect The Visitor’s Browser Using A Hook:
The problem.
Cross-browser compatibility is probably the most common problem in Web development. You will save yourself a lot of headaches if you are able to detect the browsers that people use to visit your website and then create a custom class wrapped in the body
tag. Few people are aware of it, but WordPress can already detect browsers, and a few global variables are available for us to use.
The solution.
Nothing hard here: just paste the code below in your functions.php file, then save the file and you’re done!
<?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 have saved the file, the function will automatically add a CSS class to the body
tag, as shown in the example below:
<body class="home blog logged-in safari">
Code explanation.
WordPress has global variables that return true
if a visitor is using a particular browser. If the visitor’s browser is Google Chrome, the $is_chrome
variable will return true
. This is why we create the browser_body_class()
function, which returns the name of the visitor’s browser. Once that’s done, we just hook the function to WordPress’ body_class()
function.
No Comments