Add Useragent to the body class?

I’m looking for a way to add body class depending on the User Agent of the client with php.

I’m looking to implement it this way:


<body id="front" <?php ( function_exists ( 'body_class' ) : body_class($classes) ? NULL ); ?> >

Or by using adding it to the functions.php file

FYI: The whole purpose of this is to sniff out particular mobile styles and disable javascript for the some mobile user-agents.

p.s. I’m not looking for a mobile plugin.

p.p.s. no, i’m not interested in using a mobile theme.

Solutions Collecting From Web of "Add Useragent to the body class?"

something like this maybe:

function my_class_names($classes) {
    $useragent = $_SERVER['HTTP_USER_AGENT'];
    if(strchr($useragent,'Safari')) $classes[] = 'Safari';
    // etc..
    return $classes;

Edit – as per Chip’s suggestion, here’s the function using the WordPress useragents checks:

function my_class_names($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_winIE) $classes[] = 'winIE';
    elseif($is_macIE) $classes[] = 'macIE';
    elseif($is_opera) $classes[] = 'opera';
    elseif($is_NS4) $classes[] = 'NS4';
    elseif($is_safari) $classes[] = 'safari';
    elseif($is_chrome) $classes[] = 'chrome';
    elseif($is_iphone) $classes[] = 'iphone';
    else $classes[] = 'other';
    return $classes;

Use media queries. If you change your output depending on the user agent, you have to disallow proxy caches, and even caching in local static files will become unnecessary hard. And don’t forget to send a header Vary: User Agent – this will slow down your site loading times in every browser.

See also: How To Use CSS3 Media Queries To Create a Mobile Version of Your Website.

WordPress includes global variables that store some of these useragents. Perhaps something like this:

global $is_iphone;

$classes = array();

if ( $is_iphone ) $classes[] = 'iphone';
<body id="front" <?php body_class( $classes ); ?>>

(Why are you wrapping body_class() inside function_exists()? This tag generally doesn’t need backwards-compatibility, as it was introduced in WordPress 2.8.)