Last active
July 17, 2017 23:14
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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