Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Add body classes for current page and all ancestors
* Add classes for pages and page parents
function prefix_add_specific_body_classes($classes) {
// Bail if we're not on a page
if (is_page()) {
global $post;
// If we *do* have an ancestors list, process it
if ( $parents = get_post_ancestors( $post->ID ) ) {
foreach ( (array) $parents as $parent ) {
// As the array contains IDs only, we need to get each page
if ( $page = get_page( $parent ) ) {
// Add the current ancestor to the body class array
$classes[] = "{$page->post_type}-{$page->post_name}";
// Add the current page to our body class array
$classes[] = "{$post->post_type}-{$post->post_name}";
return $classes;
// Add a filter for WP
add_filter( 'body_class', 'prefix_add_specific_body_classes' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.