WordPress.org

Make WordPress Core

Opened 6 years ago

Closed 6 years ago

Last modified 6 years ago

#31398 closed enhancement (wontfix)

Add theme function wp_add_body_class() to abstract filtering `body_class`

Reported by: mattheweppelsheimer Owned by:
Milestone: Priority: normal
Severity: normal Version:
Component: Themes Keywords: close
Focuses: template Cc:

Description

I frequently filter body_class at the top of page templates to support shared template parts, to set up those template parts' custom CSS and/or JavaScript. So I end up with a lot of this pattern at the top of templates:

add_filter('body_class', 'my_new_body_class');
function my_new_body_class( $classes ) {
        $classes[] = 'foo';
        return $classes;
}

I'd like to do something like this, instead: wp_add_body_class( 'foo' );.

This function would wrap the mechanism above. It would accept an array or a string. The advantage is speed of writing theme templates in this way, and simplicity in reading the code.

Change History (6)

#1 @mattheweppelsheimer
6 years ago

  • Keywords dev-feedback added

I would use this all the time, but I can imagine others making an argument that this isn't necessary. So, I'd like to get some dev feedback as to whether this belongs in core.

With a thumbs-up, I'll contribute a patch.

#2 @mattheweppelsheimer
6 years ago

  • Summary changed from Add theme function add_body_class() to abstract filtering `body_class` to Add theme function wp_add_body_class() to abstract filtering `body_class`

#3 @obenland
6 years ago

  • Keywords dev-feedback removed

I think the only time it would improve the developer experience would be if the theme would only need to add one class. As soon as it would have to be called more than once we're adding unnecessary callbacks to that filter. But adding one class can also be done by passing it as an argument to body_class() directly, without even having the need of using the filter.

Adding a function to wrap a filter and callback would also add to the confusion of inconsistent WordPress APIs, which makes the benefit fairly marginal in my opinion.

#4 @SergeyBiryukov
6 years ago

  • Keywords close added

#5 @mattheweppelsheimer
6 years ago

  • Resolution set to wontfix
  • Status changed from new to closed

Thanks for the feedback, @obenland. Makes sense.

I do add single classes in template parts quite often, so this frequently happens three or four times per page load in my themes. But this is probably uncommon enough to be an edge case. So, I can create my own convenience function for use when needed in themes.

Even if this turns out to be more common or desired by other theme developers, your point about API confusion is persuasive.

#6 @obenland
6 years ago

  • Milestone Awaiting Review deleted

Right, also feel free to experiment with passing them as an argument to body_class().

Note: See TracTickets for help on using tickets.