Last week, while working on a website for my daughter’s up-coming wedding, I had the need to tailor the styling for mobile devices. I didn’t like the amount of white-space above all of the headings. I am using a stock theme (which I actually bought) called Game Over by Cosmo Themes.
My requirements were:
- I needed to be able to work with any off-the-shelf WordPress theme.
- I needed to be able to drive styling based on whether or not the viewer was on a mobile device.
- I needed to be able to include custom CSS styling entries.
It seemed to me that the simplest solution would be to write a WordPress plugin to test wp_is_mobile() and add a ‘is-wp-mobile’ or ‘is-not-mobile’ class to the <body> tag. And that’s exactly what I did. Voila! Works great. Now I can use custom CSS styling using body.is-wp-mobile as a CSS qualifier.
Well, as you can guess, things didn’t stop there. I found the need to do styling based on other attributes as well. So, I went through all of the WordPress is_?() functions and came up with a list that I thought would be helpful. Perhaps I went a little overboard. The end result is the wp247 Body Classes plugin.
Here’s the list of the WordPress functions included in the first release:
The resulting Body Classes are basically the function name (with underscores changed to dashes) when the function returns true, or put a ‘not-‘ after the ‘is-‘ if the function returns false. As an example, is_home() would result in a is-home class being added to the <body> tag if you are on the home page and would result in is-not-home class if you are not on the home page.
For some of the functions tested, additional classes can be included if the function returns true. As an example, if is_author() returns true, along with the is-author class being included in the <body> tag, is-author-(author-nicename) and is-author-(author-id) may also be included – just in case some author’s are more special than others :).
Want to use this plugin on your WordPress website? It’s easy:
- Login to your website’s Dashboard
- Navigate to Plugins->Add New
- Type “wp247 body classes” in the “Search Plugins” box and press enter
- Click on the “Install” button
- Click on the “Activate Plugin” link
- Navigate to Settings->Body Classes
- Select the Body Classes you want to be added to the <body> tag of your web pages
- Start using the new Body Classes in your styling.
That’s it. Enjoy!