hsquareweb
1/13/2017 - 11:05 PM

Adding page and ancestor slugs to body class

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' );