Make WordPress Core

Opened 3 years ago

Last modified 8 months ago

#18118 new feature request

Append page slug to body_class function

Reported by: andrewsvg Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Themes Keywords: has-patch
Focuses: Cc:


I actually do this already on all of my sites, and thought this would be an obvious, amazing thing to add to the body_class function. Pretty much what you'd expect; the page-slug gets appended to the body_class, allowing for page-specific styling.

<?php body_class($post->post_name . ' '); ?>

Attachments (1)

18118.patch (800 bytes) - added by SergeyBiryukov 3 years ago.

Download all attachments as: .zip

Change History (8)

comment:1 johnbillion3 years ago

Probably needs a prefix to the slug, eg page-my-page instead of just my-page. Might be an idea to do it for all hierarchical CPTs too.

Last edited 3 years ago by johnbillion (previous) (diff)

comment:2 SergeyBiryukov3 years ago

Closed #18220 as duplicate.

comment:3 DennisSmolek3 years ago

It wont need a prefix as the body tag already gets the post type as a part of the class object. you would just use .post.page-title {}
There are two ways, one as a functions.php add on, the other as a part of the core file. You would want to check if its post/page because they have different name functions.

There is actually an example of this somewhere in the codex..

comment:4 DennisSmolek3 years ago

this looks right:
add to line 330:

$classes[] = $post->post_name;

SergeyBiryukov3 years ago

comment:5 SergeyBiryukov3 years ago

  • Keywords has-patch added

comment:6 obenland8 months ago

If page-specific styling is the purpose of this ticket, why not use the post/page ID classes?

comment:7 buffler8 months ago

There may be good reason not to worry about this... but I thought I'd just chime in to +1 - I've taken to adding a filter on body_class to achieve this same thing.

True, ID classes can be used just the same - but not having to add comments anywhere you might use them feels nicer to me. ".page.about-us" is sort of self-documenting, whereas ".page-id-###" should probably be accompanied by a comment explaining which page it is anywhere it's used...

Last edited 8 months ago by buffler (previous) (diff)
Note: See TracTickets for help on using tickets.