Lots of ways to add an ID to the `body` element
The following is a guest post by Trishah Woolley. Over the years, Trishah has collected a ton of code snippets that to the job of adding IDs and classes based on some variable information, like the URL or data from WordPress. Each of these snippets were either either collected from documentation or a similar online resource, or written by Trishah based on standard features of the language and API’s involved.
Over the time I have been doing WordPress web design, there are occasions when I have needed to add an ID or class to the tag. For example: This often happens when integrating a 3rd party into WordPress that creates its own pages that WordPress doesn’t recognize. Or I need more nuanced classes for the site design I’m creating.
To change the look of these pages in a way that the styles are scoped just to that page, we need a way to target just that page or category of pages. Below are some of the ways I have found helpful to add IDs and classes to the of both non-WordPress (but still PHP) and WordPress pages.
PHP Variations
#01 – Add ID from the URL
This will strip the forward-slash, `.php`, and the `?pg=`, from the URL and use the rest as an ID. Change the array to match your particular situation.
<?php
$page = str_replace(array('/', '.php', '?pg='), '', $_SERVER['REQUEST_URI']);
$page = $page ? $page : 'default';
?>
<body id="<?php echo $page ?>">
Example:
http://domain.com/directory/test.php?pg=12345
Becomes:
<body id="directorytest12345">
#02 – Add ID and Class from URL
This looks for the `?` in the URL and turns what comes before it into an ID and what comes after it into a class.
<?php
list($page, $class) = explode('?', $_SERVER['REQUEST_URI']);
$page = str_replace(array('/', '.php'), '', $page);
$class = str_replace(array('='), '', $class);
?>
<body id="<?php echo $page ?>" class="<?php echo $class ?>">
Example:
http://domain.com/directory/test/?pg=12345
Becomes:
<body id="directorytest" class="12345">
#03 – Add ID from file name
This removes the `.php` and uses the file name as the ID:
<body id="<?=basename($_SERVER['PHP_SELF'],'.php')?>">
Example:
http://domain.com/directory/test.php
Becomes:
<body id="test">
#04 – Add ID from First Level Directory
This will grab the first level directory and use it as the ID.
$url = explode('/', $_SERVER['REQUEST_URI']);
$dir = $url[1] ? $url[1] : 'home';
?>
<body id="<?php echo $dir ?>">
Example:
http://domain.com/directory1/directory2/test.php
Becomes:
<body id="directory1">
WordPress Variations
WordPress has a native function for applying classes to the body:
<body <?php body_class(); ?>>
Which results in output like this, depending on what page you are on:
<body class="single single-post postid-245501 single-format-standard">
But you can still do more, like combine it with techniques from above and add classes of your own.
#05 – WordPress: Add a Class to Default Body Class
Add your own class to the ones generated by WordPress with this:
<body <?php body_class('class-one ); ?>>
Becomes:
<body class="page page-id-2 page-parent page-template-default logged-in class-one">
#06 – WordPress: Add Multiple Classes to Default Body Class
You can add multiple classes like this:
<?php body_class(array("class-one", "class-two", "class-three")); ?>
Becomes:
<body class="page page-id-2 page-parent page-template-default logged-in class-one class-two class-three">
#07 – WordPress: Add ID and Class to Body Tags
This just may be my favorite! It does the same as the one above but adds the new class to the WordPress’ body_class
:
list($page, $class) = explode('?', $_SERVER['REQUEST_URI']);
$page = str_replace(array('/', '.php'), '', $page);
$class = str_replace(array('='), '', $class);
?>
<body id="<?php echo $page ?>" <?php if (function_exists('body_class')) body_class($class ); ?>>
Example:
http://domain.com/directory/test/?pg=12345
Becomes:
<body id="directorytest" and class="page page-id-2 page-parent page-template-default logged-in 12345">
#08 – WordPress: Use the Slug
<body id="<?php echo $post->post_name; ?>">
Example:
http://domain.com/category1/slug/
Becomes:
<body id="slug">
#09 – WordPress: Conditionally Add Extra Classes
This a body class to the ones generated by WordPress with conditional if()
logic. For example, here we’re using the is_shop()
boolean logic provided by WooCommerce:
<body <?php if (is_shop()) { body_class('shop'); } else { body_class(); } ?>>
Becomes:
<body class="page page-id-2 page-parent page-template-default logged-in shop">
#10 – WordPress: Add the Slug to the Body Class Defaults
We can also alter the output of the body_class()
function by filtering it. We could do this in `functions.php` or our own functionality plugin.
Here we’ll add the slug:
function add_slug_body_class( $classes ) {
global $post;
if (isset($post)) {
$classes[] = $post->post_type . '-' . $post->post_name;
}
return $classes;
}
add_filter('body_class', 'add_slug_body_class');
Example:
http://domain.com/category/page-slug/
Becomes:
<body class="page page-id-2 page-parent page-template-default logged-in page-slug">
#11 – WordPress: Add to Body Class using function.php Filter
Add the following to functions.php:
function my_body_classes( $classes ) {
$classes[] = 'class1';
return $classes;
}
add_filter('body_class', 'my_body_classes');
Then it would output like this, just calling body_class()
directly without doing anything else:
<body class="page page-id-2 page-parent page-template-default logged-in my_body_classes">
#12 – WordPress: Raw Filtering of Function using Functions.php
This is how you would add a single class of any name:
function my_body_classes( $classes ) {
$classes[] = 'class1';
return $classes;
}
add_filter('body_class', 'my_body_classes');
Becomes:
<body class="page page-id-2 page-parent page-template-default logged-in class1">
#13 – WordPress: Raw Filtering of Function using Functions.php to Add Multiple Classes, Conditionally
function my_body_classes( $classes ) {
$classes[] = 'class1';
if (is_shop()) {
$classes[] = 'shop';
}
return $classes;
}
add_filter('body_class', 'my_body_classes');
Becomes this on a non-shop page:
<body class="page page-id-2 page-parent page-template-default logged-in class1">
Becomes this if the logic comes out true
, i.e., on a shop page:
#14 WordPress: Remove Classes from Default Output using functions.php
With this you can remove classes from body_class()
:
function adjust_body_class($classes) {
foreach ($classes as $key => $value) {
if ($value == 'class-to-remove') unset($classes[$key]);
}
return $classes;
}
add_filter('body_class', 'adjust_body_class');
If we started with this:
<body class="page page-id-2 page-parent page-template-default logged-in">
And removed “page-parent”, we’d get this:
<body class="page page-id-2 page-template-default logged-in">
#15 WordPress: Add the Category
Adds the category to body_class()
:
function add_category_name($classes = '') {
if (is_single()) {
$category = get_the_category();
$classes[] = 'category-'.$category[0]->slug;
}
return $classes;
}
add_filter('body_class','add_category_name');
Example URL:
http://domain.com/category1/post-title/
Becomes:
<body class="page page-id-2 page-parent page-template-default logged-in category1">
#16 WordPress: Add the Category via functions.php Filter
You can also do it via filter:
function add_category_to_single($classes) {
if (is_single()) {
global $post;
foreach((get_the_category($post->ID)) as $category) {
// add category slug to the $classes array
$classes[] = $category->category_nicename;
}
}
// return the $classes array
return $classes;
}
add_filter('body_class', 'add_category_to_single');
Example URL:
http://domain.com/category1/post-title/
Becomes:
<body class="page page-id-2 page-parent page-template-default logged-in category1">
#17 WordPress: Add Browser Class Name
WordPress provides some Global Variables including booleans values on what browser is in use. You can add those to the body class as well:
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;
}
add_filter('body_class', 'browser_body_class');
Example with Chrome:
<body class="page page-id-2 page-parent page-template-default logged-in chrome">
Careful not to rely on these for important functionality! User agent testing, as this uses, is known for causing more problems than it solves.
Lots of ways to add an ID to the `body` element is a post from CSS-Tricks