X

Add parent page slug to body_class

Visual Composer Review

Adding this snippet to the functions.php of your wordpress theme will add the parent page slug to the body_class. Displayed like this <body class="parent-PAGESLUG"> this can be a great way if you need to style elements on specific pages.



Code Snippet:


add_filter('body_class','body_class_section');

function body_class_section($classes) {
global $wpdb, $post;
if (is_page()) {
if ($post->post_parent) {
$parent = end(get_post_ancestors($current_page_id));
} else {
$parent = $post->ID;
}
$post_data = get_post($parent, ARRAY_A);
$classes[] = 'parent-' . $post_data['post_name'];
}
return $classes;
}

Comments  Leave a Reply

  1. Works beautifully in WordPress 3.9.1, thank you!

  2. Can this be adapted to add the top ancestor to the body class? So if I navigate to a grandchild page, I see not the parent slug, but the grandparent slug?

  3. When I use this, I still get all of the BS default classes added by WP. Is there a way to filter those out?

    1. Hi Jess, ill be posting a snippet monday that will provide a solution for this. 

  4. Thanks, exactly what I was looking for. One question – could this be adapted so that it outputs not only the parent page slug in the body classes, but also the current page slug as well? This would be useful for targeting sections in CSS, plus specific pages as well.

    1. I write something so  can post it in a new few days.

      1. Thanks, looking forward to it 🙂

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!