Created
February 18, 2019 22:38
-
-
Save jonschr/300fc534e48d2d4b460cba8f9b26cba1 to your computer and use it in GitHub Desktop.
Add body classes for current page and all ancestors
This file contains 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
/** | |
* Add classes for pages and page parents | |
*/ | |
function prefix_add_specific_body_classes($classes) { | |
// Bail if we're not on a page | |
if (is_page()) { | |
global $post; | |
// 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[] = "{$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 a filter for WP | |
add_filter( 'body_class', 'prefix_add_specific_body_classes' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment