Add parent page slug to body_class

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.



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;

Leave a comment