0

Is there a way to add classes to the body_class function based on the current page?

For example if you're on the homepage, as well as the usual generated classes, the <body> element would also have front and main-page classes. Then if you were on the "About" page it would have inner-page and sixcol classes instead.

I (unsuccessfully) tried this;

function body_class_variants($variants) {

if (is_home() || is_front_page()) {
    $variants = 'front main-page';
} else {
    $variants = 'inner-page sixcol';
}
return $variants;

add_filter('body_class','body_class_variants');

which was based off this function that I use to output the page name into the body class

function body_class_names($classes) {
global $post;
$name = $post->post_name;
$classes[] = $name;
return $classes;
}

add_filter('body_class','body_class_names');

But to no avail.

Any help would be greatly appreciated.

3
  • I've copy and pasted your filter function and it worked in my theme just as expected.
    – Howdy_McGee
    Commented Jul 28, 2014 at 16:20
  • That code looks just fine.. Have you checked your theme to make sure the <?php body_class(); ?> function is added to the body tag? It should look like <body <?php body_class(); ?>>. See codex.wordpress.org/Function_Reference/body_class Commented Jul 28, 2014 at 16:48
  • 1
    Can you explain how the body_class_variants function is failing? It looks to me like you are overwriting and not returning the existing variants, rather than adding to the array as you do in body_class_names Commented Jul 28, 2014 at 17:22

2 Answers 2

-1

I do what you're trying to do by adding it directly to the body tag. Example on how to add a class to interior pages.

<body <?php if(!is_front_page()){body_class('interior-page');}else{body_class();} ?>>
1
  • 1
    I'm trying to keep my main templates as clean as possible, the site I'm working on (It's a theme conversion) requires a lot of different classes for different pages so doing it this way would make things very untidy Commented Jul 28, 2014 at 16:00
-1

Another option could be doing it very jQuery on page load...

$( document ).ready(function() {

    // get url and assign to variable
    url = $(location).attr('href');

    // Split into an array if needs be
    splitUrl = url.split( '/' );

    // Log a segment if you want too
    splitUrl[3];

 if(splitUrl[3] == "about") {
    $("body").addClass("about")
 }

});

Although i would add that gdaniels answer above would be a much better option as you would be dealing with the change when the php parsed. Where as with jQuery you are manipulating the dom after page load (far less desirable and with larger overheads).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.