A better body-class function for WordPress
UPDATE– Jan. 25, 2015: moving the parent page name checks into the conditional statement to avoid silent errors // UPDATE– Oct. 20, 2013: Thanks to Marty (see comments below), for convincing us to change out our method for body classes to filter the default WP body_class() function instead of creating our own. It still gives you all the advantages of our original function plus the classes you get by default.
Here’s what it does
- First, check to see if you are on one of the following and create a class if so: home, 404, category, search, tag.
- We then make a class prefixed by page_ that has the name of the page or post in it.
- Then we check to see if the page has a parent, if so, we create a class prefixed by parent_ and put the parent name there.
- Finally we make a class with the prefix template_ and put the name of the template used there.
The PHP
Add this stuff to your functions.php file, or just use our html5 shell and it’s built in.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// Add to the body_class function function condensed_body_class($classes) { global $post; // add a class for the name of the page - later might want to remove the auto generated pageid class which isn't very useful if( is_page()) { $pn = $post->post_name; $classes[] = "page_".$pn; } // add a class for the parent page name if ( is_page() && $post->post_parent ) { $post_parent = get_post($post->post_parent); $parentSlug = $post_parent->post_name; $classes[] = "parent_".$parentSlug; } // add class for the name of the custom template used (if any) $temp = get_page_template(); if ( $temp != null ) { $path = pathinfo($temp); $tmp = $path['filename'] . "." . $path['extension']; $tn= str_replace(".php", "", $tmp); $classes[] = "template_".$tn; } return $classes; } add_filter('body_class', 'condensed_body_class'); |
The HTML
1 2 3 |
<body class="<?php body_class(); ?>"> |
Your Help
Let us know if you see ways to make it better, probably more conditions could be added to the beginning to take into consideration more template types.
Topics covered: body class wordpresscustom template namefunctionsparent pagephpwordpress