Add Browser Specific Custom Body & Post Class

On my previous post, I explained how to display custom message based on user’s web browser. Interestingly today I will discuss something pretty similar but with a little twist on it. Ready for the ride? let’s roll.

I will discuss how to add custom body class based on user’s web browser and style them using CSS. Definitely the very first thing that we need to do is to detect user’s browser type and then add classes. Let’s take a look at some of these WordPress global variables. We can use these variables to detect various types of browsers. Here is the outcome that we are talking about here.

Custom CSS ClassCustom Body Class in WordPress.

Now, before we discuss our snippet please remember that you must have body_class function on your opening <body> tag. In other words, your body tag should look like this.

<body <?php body_class($class); ?>>

Now, let’s take a look at our long waited snippet. This is fairly simple and easy to understand.

<?php
add_filter('body_class','add_custom_browser_class');
function add_custom_browser_class ($classes) {
   global $is_iphone, $is_chrome, $is_winIE;
      if ($is_iphone) { $classes[] = 'iphone'; } 
      if ($is_chrome) { $classes[] = 'chrome'; } 
      if ($is_winIE) { $classes[] = 'winie'; }
   return $classes; 
}
?>

Simply copy and paste this snippet above on your theme's functions.php page and update it. Next things is styling your body class with CSS. Show your creativity with that.

What about Post Class?

This snippet works equally well with post_class function. Our snippet could be particularly useful for pages like single.php or page.php. Even though you can use it anywhere within the loop.

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

And ofcourse, don't forget to change the filter hook on our snippet. It should be like this:

<?php
add_filter('post_class','add_custom_browser_class');
?>

Rest of the snippet remains as it is. Hope you got my point.

Today In History

  •  
  •  

Comment

Leave a Reply

Note: Convet HTML, PHP, JavaScripts from Postable, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.