
Detect Browser Using Hook Function
- January 25, 2017
- Leave a comment
Sometimes, you might need to serve a specific content on certain Web browsers. There are many ways to fulfill this purpose but within WordPress, you can use WordPress built-in global variables. Many people don’t know that WordPress provides several global variables that can be used to detect browsers.
Below is a list of these global variables:
- $is_lynx (for Linux)
- $is_gecko (for Firefox)
- $is_IE (for Internet Explorer)
- $is_winIE (for Windows)
- $is_macIE (for MAC)
- $is_opera (for Opera)
- $is_NS4 (for NS4)
- $is_safari (for Safari)
- $is_chrome (for Chrome)
- $is_iphone (for iPhone)
.
All variables are set to FALSE by default and will only be TRUE if a preset condition is true. Let us assume that if a user loads a page using Chrome then the variable $is_chrome will be TRUE.
Now we understand the simple way that WordPress provides us with, to detect browsers. Thus, we can add detected values as a class in the body tag using body_class hook. Add the following code in functions.php file and then load your WP site. Check that the body tag will have browser name as a class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
// detect browser and add browser name as a class in body tag function detect_browser_body_class($classes) { global $is_lynx, $is_firefox, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone; if($is_lynx) { $classes[] = 'lynx'; } elseif($is_gecko) { $classes[] = 'firefox'; } 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','detect_browser_body_class'); |
Once everything is done, then you can see the browser name in the HTML body tag using browser inspect tool.
User Comments