WordPress hack: Extend the body_class function

by Jean-Baptiste Jung on November 2, 2009

Nothing hard at all. Paste the following code in your function.php file :

add_filter('body_class','top_level_parent_id_body_class');
function top_level_parent_id_body_class($classes) {
	global $wpdb, $post;
	if (is_page()) {
	    if ($post->post_parent)	{
        	$ancestors=get_post_ancestors($post->ID);
        	$root=count($ancestors)-1;
        	$parent = $ancestors[$root];
        } else {
        	$parent = $post->ID;
        }
        $classes[] = 'top-level-parent-pageid-' . $parent;
	}
	return $classes;
}

Once your functions.php file is saved, you're done.

Thanks to Mr Henry for this very cool recipe!

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

WordPress hack: Extend the body_class function