Remove and add class with body_class() function

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;
}

Leave a Comment

tech