WordPress has some handy conditional functions (conditional tags as stated on WP Developers Theme Handbook), such as is_post, is_home and is_page. Unfortunatelly, is_page doesn’t find child and grandchild pages.
Luckily, if you search for help around the interwebz you will find is_tree
, a function that finds child and grandchild pages. It’s even mentioned on Developer Handbook, which makes me wonder why is not in WP core yet.
is_tree conditional – extended version
For a while, I’ve been using is_tree conditional in a extended version which allows the use of page slugs, and not only IDs. It’s available on Github.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | /** * is_tree extended function. * * Extends the typical is_tree function -- as found in WordPress Theme Handbook ( https://developer.wordpress.org/themes/basics/conditional-tags/ ) and CSS Tricks ( https://css-tricks.com/snippets/wordpress/if-page-is-parent-or-child/ ) -- and allows it to find if a page is child or grandchild of another page by it's slug * * @access public * @author Celso Bessa <celso.bessa@2aces.com.br> * @see https://celsobessa.com.br/2017/07/17/is-tree-conditional-extended/ * @param mixed $page * @param bool $use_slug if set to true, (default: false) * @return bool true if a page is child or grandchild of another page */ function is_tree( $page_id, $use_slug = false ) { if ( $use_slug === true && !is_string( $page_id ) ) { return false; } else if ( $use_slug !== true && !is_int( $page_id ) ) { return false; } if ( $use_slug === true ) { $page_data = get_page_by_path( $page_id ); if ( null === $page_data ) { return false; } $page_id = $page_data->ID; } global $post; // load details about this page if( is_page( $page_id ) ) { return true; // we're at the page or at a sub page } $anc = get_post_ancestors( $post->ID ); foreach ( $anc as $ancestor ) { if( is_page() && $ancestor == $page_id ) { return true; } } return false; // we're elsewhere }; |
Hope it helps.