WordPress Snippets at WPcustoms

Add parent page slug to the body class

Use custom css stylings for parent \ sub page sections. This function adds “section-slug” to the body_class() where slug is the name of the parent page. This way you can easily set custom background colors for child pages for each parent page.

 * Snippet Name: Add parent page slug to the body class
 * Snippet URL: https://wpcustoms.net/snippets/add-parent-page-slug-body-class/
  // example usage: .section-about { background: red; }
function wpc_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[] = 'section-' . $post_data['post_name'];
    return $classes;