Created
September 4, 2013 14:53
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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