Skip to content

Instantly share code, notes, and snippets.

@hsquareweb
Created January 13, 2017 23:05
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 hsquareweb/2e2d9f8fdad6bed8cba3dc6888b97125 to your computer and use it in GitHub Desktop.
Save hsquareweb/2e2d9f8fdad6bed8cba3dc6888b97125 to your computer and use it in GitHub Desktop.
Adding page and ancestor slugs to body class
//Page Slug Body Class
function add_slug_body_class( $classes ) {
global $post;
#Post
if ( isset( $post ) ) {
$classes[] = $post->post_type . '-' . $post->post_name;
}
#Ancestors
if (is_page()) {
// If we *do* have an ancestors list, process it
// http://codex.wordpress.org/Function_Reference/get_post_ancestors
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[] = "parent-{$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_filter( 'body_class', 'add_slug_body_class' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment