Detect The Visitor’s Browser Using A Hook

Detect The Visitor’s Browser Using A Hook

Sm2 in 10 Useful WordPress Hook Hacks

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!

01 <?php
02 add_filter('body_class','browser_body_class');
03 function browser_body_class($classes) {
04     global $is_lynx$is_gecko$is_IE$is_opera$is_NS4$is_safari$is_chrome,$is_iphone;
06     if($is_lynx$classes[] = 'lynx';
07     elseif($is_gecko$classes[] = 'gecko';
08     elseif($is_opera$classes[] = 'opera';
09     elseif($is_NS4$classes[] = 'ns4';
10     elseif($is_safari$classes[] = 'safari';
11     elseif($is_chrome$classes[] = 'chrome';
12     elseif($is_IE$classes[] = 'ie';
13     else $classes[] = 'unknown';
15     if($is_iphone$classes[] = 'iphone';
16     return $classes;
17 }
18 ?>

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

1 <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 thebrowser_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.




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s