in WordPress

Change style depending on User Browser in Wordpress

In wordpress it is possible to change the body tag class to something depending on the browser the user is on. This is done by using a hook with a filter to add extra classes to the array for the body class. Wordpress has a number of in-built functions that returns a variable for the browser the user is using, therefore you can use these variables to change the classes in the body tag. Copy and paste the below snippet into your functions.php file.


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;
}

Now you can change the change of the elements in your CSS files by prefixing them with the defined browser tag.


body.chrome{
    font-size:12px;
}
body.ie{
    font-size:24px;
}

This will now show the font much larger when using Internet Explorer than when using Google Chrome.

Subscribe To The Weekly Newsletter

Get weekly updates to your email