I am trying to grab a specific ancestor title and only add it as a body class to the grandchild page. For example I have a page URL of "www.example.com/products/educational/fume-hoods/airfoil/" So I'm on the "airfoil" page and I want to grab the ancestor page name "educational" and only add it as a body class to the page "airfoil". But at the same time apply it to any page that has the "educational" ancestor page.
Everything I have tried, adds it globally. This was one I tired:
if ( is_page() ) {
global $post;
if ( $post->post_parent ) {
$ancestors = get_post_ancestors( $post->ID );
$root = count( $ancestors ) - 1;
$top_id = $ancestors[$root];
$top_pg = get_page( $top_id );
$top_cat_pg = $top_pg->post_name;
} else {
$top_cat_pg = $post->post_name;
}
}
$class[] = $prefix . $top_cat_pg;
return $class;
I also tried:
function add_body_class( $class ) {
if ( is_page() ) {
$ancestors = get_post_ancestors( $post->ID );
if ($ancestors === '6421'){
$class = 'educational';
}
return $class;
So the ancestor post ID is 6421. So my logic is: if is_page then get_post_ancestor, if ancestor ID is equal to 6421 then add body class "educational'.
question from:
https://stackoverflow.com/questions/66068073/php-if-page-has-ancestor-id-then 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…