Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

wordpress - PHP if page has ancestor ID then

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...