3

I want to remove the default body class on the theme and add a new class.

I use this code to do this:

//REMOVE / ADD HOME CLASS FROM BODY

add_filter('body_class', function (array $classes) {
    if (in_array('home', $classes)) {
      unset( $classes[array_search('home', $classes)] );
    }
  return $classes;
});

add_filter('body_class', function (array $classes) {
    if (in_array('blog', $classes)) {
      unset( $classes[array_search('blog', $classes)] );
    }
  return $classes;
});



add_action( 'body_class', 'my_custom_class');
function my_custom_class( $classes ) {
  $classes[] = 'my-custom-class';
  return $classes;
}

The code works because the two default classes disappear and the new class appears, but when I create "my_custom_class" in style.css, the CSS doesn't work.

I tried to modify the margin for example, I use this code:

.my_custom_class {
    margin-top: 350px !important;
}

but on site there are no changes.

1

The my_custom_class() function is using the class name my-custom-class, but the CSS is targeting the class my_custom_class. These two strings should be exactly the same:

.my-custom-class {
    margin-top: 350px !important;
}

Also, it would be a little cleaner to handle all of the body_class stuff in a single callback function:

add_action( 'body_class', 'my_custom_class');
function my_custom_class( $classes ) {
    // Remove 'blog' class
    if (in_array('blog', $classes)) {
        unset( $classes[array_search('blog', $classes)] );
    }

    // Remove 'home' class
    if (in_array('home', $classes)) {
        unset( $classes[array_search('home', $classes)] );
    }

    // Add custom class
    $classes[] = 'my-custom-class';

    return $classes;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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