DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

Introduced in WordPress 2.7 the body_class() function is extremely useful to style a particular post, page or subpage. But when we look at the subsubpages, the parent page ID is that of it’s nearest parent and not the ID of it’s top level parent. Let’s solve this issue.

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

function top_level_parent_id_body_class($classes) {
	global $wpdb, $post;
	if (is_page()) {
	    if ($post->post_parent)	{
        	$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!


Leave a Comment

Your email address will not be published. Required fields are marked *