Post Pic

WordPress hack: Extend the body_class function

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 :

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!

7 Responses

Nov 04 2009 05:27

要玩黑彩吗?

Nov 06 2009 10:46

Don’t understand what the previous comment says, so if someone knows, please share :) . Maybe I can help the fella with his question.

Nov 06 2009 11:04

Or.. it’s just chinese spam :)

Nov 19 2009 18:27

Well, according to Google Translator, it says:

The black color do we want to play?

Nice extension, anyway :-)

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required