Do you want to customize the CSS for specific pages? Adding the parent page slug to the body_class is a great way to target a specific page with CSS. That way you can easily identify the class of the element you want to change.
Instructions:
All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:
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; }
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 62 best free WordPress blog themes or 7 best WordPress contact form plugins.
Works beautifully in WordPress 3.9.1, thank you!
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?
When I use this, I still get all of the BS default classes added by WP. Is there a way to filter those out?
Hi Jess, ill be posting a snippet monday that will provide a solution for this.
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.
I write something so can post it in a new few days.
Thanks, looking forward to it 🙂