Home / functions.php / Add parent page slug to body_class
  • How to Add parent page slug to body_class

    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.

    ( click code to copy )

    wordpress snippet : PHP

    <>
    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;
    }
    

    ( WordPress codex functions, hooks, in this snippet. )

    body_class, get_post, get_post_ancestors, is_page, add_filter, _n, wp,
  • Matt

    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.

      • Matt

        Thanks, looking forward to it :)

  • 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. 

  • Toby

    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?

  • Cory W

    Works beautifully in WordPress 3.9.1, thank you!