Skip to content

Instantly share code, notes, and snippets.

@krusynth
Created September 4, 2013 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krusynth/6438082 to your computer and use it in GitHub Desktop.
Save krusynth/6438082 to your computer and use it in GitHub Desktop.
Wordpress theme addition to add the page's slug, and the page's oldest ancestor's slug to the body class. Very useful for hierarchies.
function get_top_level_page() {
global $top_level_page;
global $post;
// Get global page heading
if( is_page() && !$top_level_page) {
/* Get an array of Ancestors and Parents if they exist */
$parents = get_post_ancestors( $post->ID );
/* Get the top Level page->ID count base 1, array base 0 so -1 */
if($parents) {
$id = $parents[count($parents)-1];
}
else {
$id = $post->ID;
}
/* Get the parent and set the $class with the page slug (post_name) */
$top_level_page = get_page( $id );
}
}
add_action('wp_head', 'get_top_level_page');
// Add post slug to body class
function add_body_class( $classes )
{
global $post;
if ( isset( $post ) ) {
$classes[] = $post->post_type . '-' . $post->post_name;
}
if( is_page() ) {
get_top_level_page();
global $top_level_page;
if($top_level_page) {
$classes[] = $post->post_type . '-' . $top_level_page->post_name;
}
}
return $classes;
}
add_filter( 'body_class', 'add_body_class' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment