A better body-class function for WordPress

UPDATED– October 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.


// 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
    $post_parent = get_post($post->post_parent);
    $parentSlug = $post_parent->post_name;
    
    if ( is_page() && $post->post_parent ) {
            $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


<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.

« previous postnext post »

2 Comments

  • Marty Thornley

    You can add or remove any classes you want using the ‘body_class’ filter. I personally use the body classes all the time but if you want simpler, it’s easy to filter it to be whatever you want.

    return apply_filters( ‘body_class’, $classes, $class );

    http://core.trac.wordpress.org/browser/tags/3.5.1/wp-includes/post-template.php#L0

    • Brent Lagerman

      Thanks Marty, you’ve convinced me to retire our function in favor of a filter on the body_class function… My main gripe with it is that it returns SO much crap I don’t need and not some of the obvious stuff a themer would want… Thanks for pointing out this method though, it seems like a better way to do it.