css - Add top parent page id to body class

admin2025-01-07  6

I need to have the top parent page id added to the body class of the pages.

Homepage (id:10) - Sub page (id:11) -- Sub detail page (id:12)

By default it's like: Sub page gets parent Id 10 in the body class. And Sub detail page gets parent Id 11 in the body class.

What I need is that the sub page detail needs to get the upper top parent id added to the body class so that id 10 is added to the body.

The only thing I can find is what it's by default. How can I achieve this?

I need to have the top parent page id added to the body class of the pages.

Homepage (id:10) - Sub page (id:11) -- Sub detail page (id:12)

By default it's like: Sub page gets parent Id 10 in the body class. And Sub detail page gets parent Id 11 in the body class.

What I need is that the sub page detail needs to get the upper top parent id added to the body class so that id 10 is added to the body.

The only thing I can find is what it's by default. How can I achieve this?

Share Improve this question asked Jun 3, 2020 at 7:29 n00blyn00bly 1234 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

found it:

add_filter( 'body_class', 'dc_parent_body_class' );
    function dc_parent_body_class( $classes ) {
        if( is_page() ) { 
            $parents = get_post_ancestors( get_the_ID() );
            $id = ($parents) ? $parents[count($parents)-1]: get_the_ID();
        if ($id) {
            $classes[] = 'top-parent-' . $id;
        } else {
            $classes[] = 'top-parent-' . get_the_ID();
        }
    }

    return $classes;
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736256633a377.html

最新回复(0)