Home / functions.php / Browser detection and OS detection with body_class
  • How to Browser detection and OS detection with body_class

    browser-detection-and-os-detection-with-body_class

    Add the first snippet to the functions.php of your wordpress theme then add the second snippet within the body tag of your wordpress header.php template.
    <body <? body_class(); ?>>
    This snippet will add class based on the users operating system “windows, mac, linux” and also the browser including iphone and if Internet explorer the specific version.

    This wordpress snippet is an updated version of the browser detection post based on a snippet from Matt Varone and Nathan Rice.

    wordpress snippet : PHP - functions.php

    <>
    	function mv_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';
    			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','mv_browser_body_class');
    
    

    wordpress snippet : PHP - header.php

    <>
    <?php body_class(); ?>
    

    ( WordPress codex functions, hooks, in this snippet. )

    body_class, add_filter, _n, wp,
  • http://www.lonchbox.com lonchbox

    Thanx for this snippet, but is possible to also identify the windows version?, like XP, Win 7 and Win 8?