Created
January 13, 2017 23:05
-
-
Save hsquareweb/2e2d9f8fdad6bed8cba3dc6888b97125 to your computer and use it in GitHub Desktop.
Adding page and ancestor slugs to body class
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
//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