If Page Is Parent or Child

There are built in conditional WordPress functions for testing for a page:

if ( is_page(2) ) {
  // stuff
}

Or for testing if a page is a child of a certain page:

if ( $post->post_parent == '2' ) {
  // stuff
}

But there is no built in function that combines these two things, which is a fairly common need. For example, loading a special CSS page for a whole "branch" of content. Like a "videos" page and all its children individual videos pages.

This function (add to functions.php file) creates new logical function to be used in this way:

function is_tree($pid) {      // $pid = The ID of the page we're looking for pages underneath
	global $post;         // load details about this page
	if(is_page()&&($post->post_parent==$pid||is_page($pid))) 
               return true;   // we're at the page or at a sub page
	else 
               return false;  // we're elsewhere
};

Usage

if (is_tree(2)) {
   // stuff
}

Comments

  1. User Avatar
    Paul
    Permalink to comment#

    Hey,

    how can I make it work with categories?

    if I just replace ‘is_page’ with ‘is_category’ it is true for the category overview but not for alle the articles in it..

    Paul

  2. User Avatar
    Dominic
    Permalink to comment#

    This is good, but it only works one level deep.

    From the WordPress Codex:
    “Note that if you have more than one level of pages the parent page is the one directly above and not the one at the very top of the hierarchy.”

    See more about this at the WP Codex: Conditional Tags

    P.S.
    I hope noone made a buck out of this snippet, it’s straight from the wordpress codex.

    • User Avatar
      Port 80
      Permalink to comment#

      NB I had this problem ‘only works one level deep’

      But this function works with all ‘ancestors’ not just single level ‘child’ pages

      also take straight from the WP codex http://codex.wordpress.org/Conditional_Tags function

      function is_tree($pid)
      {
        global $post;
      
        $ancestors = get_post_ancestors($post->$pid);
        $root = count($ancestors) - 1;
        $parent = $ancestors[$root];
      
        if(is_page() && (is_page($pid) || $post->post_parent == $pid || in_array($pid, $ancestors)))
        {
          return true;
        }
        else
        {
          return false;
        }
      };
      
    • User Avatar
      Rams
      Permalink to comment#

      Port 80! MAARRRYY MEEEE.

      Thanks.

    • User Avatar
      erez
      Permalink to comment#

      Port 80 – Thank you!

    • User Avatar
      Andy Ford

      Port 80’s is_tree() function does the trick but will throw a Notice if PHP notices are turned on. As a workaround I added:

      if ( $root < 0) { return false; }

      just after:

      $root = count($ancestors) - 1;

      and just before:

      $parent = $ancestors[$root];

      Haven't done a ton of testing but so far this seems to be working as expected.

    • User Avatar
      Andy Ford

      Well my “greater than” angle bracket got escaped but here’s the idea:

      if ($root [LESS THAN] 0) { return false; }

  3. User Avatar
    Devin

    Nice snippet here!

  4. User Avatar
    Brenna
    Permalink to comment#

    How can you use this if you don’t want to specify a certain page ID. I need to be able to check dynamically if any current page I happen to be on is part of a branch (whether it’s the parent or child), and if so, then output a menu depending on whatever page ID it automatically retrieves.

    Any help or suggestions would be appreciated.

  5. User Avatar
    Jo
    Permalink to comment#

    Thanks for this! :)

  6. User Avatar
    Ryan Burnett
    Permalink to comment#

    Thank you! Needed this for my WordPress theme sidebar :)

  7. User Avatar
    Keri

    Cool, thanks so much for posting this! Very useful =)

  8. User Avatar
    orangerie

    Just great, thanks !

  9. User Avatar
    Leo Gono
    Permalink to comment#

    Great tutorial! Thanks! I also have another approach on this.

    
    <?php  global $post; 
    if ( is_page('2') || $post->post_parent == '2'){
    	//stuff if page has id of 2 and its subpages
    }
    else {
    	//stuff if not
    }
    ?>
    
    • User Avatar
      Leo Gono
      Permalink to comment#

      i figure it out that the above tutorial is better than my approach. I’m going to use that approach from now on.

  10. User Avatar
    Ryan
    Permalink to comment#

    Had to tackle this today and the below worked perfectly for me (works with any nesting level)

    
    if (is_page(27) || in_array(27, $post->ancestors))
    {
       // stuff if your page has ID of 27 or is a subpage (any nested level) of page ID 27
    }
    
    
    • User Avatar
      James
      Permalink to comment#

      Thanks man, this is what I needed.

    • User Avatar
      Gil
      Permalink to comment#

      Hey Ryan. this is exactly what I was missing.. thanks for posting that!

    • User Avatar
      Seth
      Permalink to comment#

      So glad you posted this! Port 80s code really didn’t make a lot of sense… this was super short and efficient and did exactly what I needed to do without a lot of random variables that add confusion :)

      Thanks!

  11. User Avatar
    Loncey Craig
    Permalink to comment#

    Hi there,
    I’m just wondering about this coding. I have a website that I’m building where the Parent has Child pages. Eg… I have a Parent page that is called:

    ABOUT US (parent page)
    Company Overview (child page)
    Director (child page)

    The company Overview page is fine because its the same page as about page. But when I click on Director Page I want the Parent Page “ABOUT US” to be highlighted as well. So both pages would be highlighted the child and parent page. The coding I’ve done is really simple. Its as follows

    ABOUT US – nav coding.

    <a class="about_us" href="”

    >

    and DIRECTOR – nav coding.

    <a href="”
    class=”director”>

    Is there a coding where I can say if the parent page we are on is “ABOUT US” to make it show it selected as well? Can you write me an example please

    Thanks in Advance.
    Oh and the link for the website is http://www.fairwayviewapartmentssamoa.com

  12. User Avatar
    Matthew Taylor
    Permalink to comment#

    Thank you tremendously for sharing this. I have come across your site multiple times now while searching for help on various things. Keep it up, and tank you again.

  13. User Avatar
    David Becerra
    Permalink to comment#

    Anyway of making this work by slug?

    I imagine we’d have to get the id from the slug.

    I’m gonna play around some this weekend.

    • User Avatar
      Zack Andrews

      Not sure if you ever figured this out, but for those who want to know:

      Add this to functions:

      function is_tree($pid) {
      	global $post;
      	if(is_page()&&($post->post_parent==$slug||is_page($slug)))
                     return true; 
      	else
                     return false;
      };

      In order to make this work for the slug instead of the page ID. And yes, the $pid is needed in the function call, I’m not sure the exact reason but $slug doesn’t work there.

  14. User Avatar
    Brandon Cook
    Permalink to comment#

    This was exactly what I needed!!!

    I was trying to edit the submenu navigational links on pages based on the child of a parent.

    In a nut shell, when on a child page, I needed the nav menu to reflect the links of the parent of the child not the child itself.

    This tutorial helped to push me in the right direction. Now I can add a custom class to the current page!

  15. User Avatar
    Mike Stimson
    Permalink to comment#

    This worked perfectly.

    Thank you very much.

  16. User Avatar
    rena
    Permalink to comment#

    Hello,
    This is exactly what i need. And the best thing is, your snippet works like a charm! thank you so much :)

  17. User Avatar
    Nick Overman
    Permalink to comment#

    Thanks so much for this! It totally saved my butt

  18. User Avatar
    Mike
    Permalink to comment#

    I use this function on almost every project!

    if (have_problem()) {
    go to css-tricks.com
    }

  19. User Avatar
    Bojan
    Permalink to comment#

    This is what i was looking for.

    Thanks.

  20. User Avatar
    Adam Nguyen
    Permalink to comment#

    Great tip.
    Thanks for sharing :)

  21. User Avatar
    Rams
    Permalink to comment#

    Still loving this one (: cheers

  22. User Avatar
    Niko
    Permalink to comment#

    You could do is like this:

    function tree(){
      $class = '';
      if( is_page() ) { 
      global $post;
          /* Get an array of Ancestors and Parents if they exist */
      $parents = get_post_ancestors( $post->ID );
          /* Get the top Level page->ID count base 1, array base 0 so -1 */ 
      $id = ($parents) ? $parents[count($parents)-1]: $post->ID;
         /* Get the parent and set the $class with the page slug (post_name) */
      $parent = get_page( $id );
      $class = $parent->post_name;
    }
    return $class;
    }
    

    and you can cale it this way:

    if(tree()=="myPageSlug1"){ echo" Hello World" }
    

    Now you get an Hello World on every childpage of myPageSlug1

  23. User Avatar
    Jay

    Sweet. Saved my butt!

  24. User Avatar
    Chris
    Permalink to comment#

    How do you write a function that checks if $post->post_parent is equal to one or another id instead of just a single id?

  25. User Avatar
    Mirko y3B4ch
    Permalink to comment#

    Chris, why dont you lock this topic as well. You already closed a shit load of other useful topics.

  26. User Avatar
    Cumhur Günay
    Permalink to comment#

    İs there a any code or condition that is check that the current page has a subpage or not. I dont mean that the current page has a parent page or not.

    • User Avatar
      Cumhur Günay
      Permalink to comment#

      İ got it :)))

      query(array(‘post_type’ => ‘page’));
      $id = $post->ID;

      $children = get_page_children( $id, $all_wp_pages );
      if($children) {
      echo “Parent”;
      }
      ?>

    • User Avatar
      Cumhur Günay
      Permalink to comment#

      Correction of Code.

      query(array(‘post_type’ => ‘page’));?>
      <?php $id = $post->ID;

                  $children = get_page_children( $id, $all_wp_pages ); ?>
                  <?php if($children) { ?>
                      <h1>Parent</h1> 
                  <?php } else { ?>
                      <h1>Child</h1>  
                  <?php } ?>
      
  27. User Avatar
    Mark Johnson
    Permalink to comment#

    Here’s my direction. Hopefully it’s helpful to someone looking to show both contingent depth and specific subpage content. I’m using the list_pages_at_depth(); plugin here. Looks for children on the second and third levels, then shows some pages.

  28. User Avatar
    Scott Brown
    Permalink to comment#

    Really helpful, thanks so much

  29. User Avatar
    Phil Cook
    Permalink to comment#

    Created a function to look at the current page and any parent pages, it searches through the hierarchy one by one looking to match against the slug URL. I choose the slug URL rather that ID as these are always different between our local, staging and production enviroments but the URL stays consistant.

    I created a gist for this here.

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-searchicon-staricon-tag