Skip to content

Instantly share code, notes, and snippets.

@2aces
Last active July 17, 2017 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 2aces/f1b1f1f9eb342b07bbe463be843b4759 to your computer and use it in GitHub Desktop.
Save 2aces/f1b1f1f9eb342b07bbe463be843b4759 to your computer and use it in GitHub Desktop.
An extended version of WordPress is_tree and is_page conditionals for finding if a page is child or grandchild of another page by it's slug
/**
* 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://www.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
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment