March 08, 2017
Incredibly handy function that I wish I found ages ago!
WordPress natively supports adding the class “parent-pageid-##” to child pages, but does not do so to ancestor pages. Thanks to TechTabby for putting this function together.
Place the code in your functions file. Class names can be updated based on preference.
Default Function from TechTabby:
add_filter( 'body_class', 'dc_parent_body_class' ); function dc_parent_body_class( $classes ) { if( is_page() ) { $parents = get_post_ancestors( get_the_ID() ); $id = ($parents) ? $parents[count($parents)-1]: get_the_ID(); if ($id) { $classes[] = 'top-parent-' . $id; } else { $classes[] = 'top-parent-' . get_the_ID(); } } return $classes; }
Modification of Class name:
add_filter( 'body_class', 'dc_parent_body_class' ); function dc_parent_body_class( $classes ) { if( is_page() ) { $parents = get_post_ancestors( get_the_ID() ); $id = ($parents) ? $parents[count($parents)-1]: get_the_ID(); if ($id) { $classes[] = 'ancestor-pageid-' . $id; // update the class name in the brackets } else { $classes[] = 'ancestor-pageid-' . get_the_ID(); // update the class name in the brackets } } return $classes; }