1

I need to remove specific body classes added as a comma separated delimited list to a custom field input field like this

wp-custom-logo, single-post, postid-28, single-format-standard, logged-in, admin-bar

Using this code only allows me to remove 1 class

add_filter('body_class', function (array $classes) {

if ( ! is_singular(array( 'post', 'page' ) ) ) {
    return;
}

$body_classes = get_post_meta( get_the_ID(), '_remove_body_classes', true );

unset( $classes[array_search($body_classes, $classes)] );

return $classes;

});

This code works when trying to remove 1 class on single posts but doesn't work when using a comma delimited list and also doesn't work on single pages.

1 Answer 1

1

One (untested) suggestion is to replace:

unset( $classes[array_search($body_classes, $classes)] );

with

$classes = array_diff( $classes, wp_parse_slug_list( $body_classes ) );

assuming the classes survive sanitize_title from wp_parse_slug_list(). It should also be alright with empty arrays.

We also note that wp_parse_slug_list() is using wp_parse_list() to parse the comma separated string.

2
  • 1
    Awesome stuff, been banging my head against the wall for hours trying to fix this. You're a rockstar @birgire Commented Jun 14, 2022 at 14:14
  • Great, glad to hear it worked for you @Michelle
    – birgire
    Commented Jun 14, 2022 at 14:15

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.