Skip to content

Instantly share code, notes, and snippets.

@srikat
Last active February 25, 2016 01:11
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 srikat/9e6ed183b9b7416418f5 to your computer and use it in GitHub Desktop.
Save srikat/9e6ed183b9b7416418f5 to your computer and use it in GitHub Desktop.
Useful functions for checking for Pages and their children/parent in WordPress. https://sridharkatakam.com/useful-functions-checking-pages-sub-pages-wordpress/
// To check a Page by ID for that Page or its direct descendants (sub/child pages)
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
}
// To check a Page by ID and all its child Pages incl. grand children
function is_tree( $pid ) { // $pid = The ID of the page we're looking for pages underneath
global $post; // load details about this page
$anc = get_post_ancestors( $post->ID );
foreach( $anc as $ancestor ) {
if ( is_page() && $ancestor == $pid ) {
return true;
}
}
if ( is_page() && ( is_page ( $pid ) ) ) {
return true; // we're at the page or at a sub page
}
else {
return false; // we're elsewhere
}
}
function is_ancestor( $post_id ) {
global $wp_query;
$ancestors = $wp_query->post->ancestors;
if ( in_array( $post_id, $ancestors ) ) {
$return = true;
} else {
$return = false;
}
return $return;
}
/**
* Child page conditional
* @ Accept's page ID, page slug or page title as parameters
*/
function is_child( $parent = '' ) {
global $post;
$parent_obj = get_page( $post->post_parent, ARRAY_A );
$parent = (string) $parent;
$parent_array = (array) $parent;
if ( in_array( (string) $parent_obj['ID'], $parent_array ) ) {
return true;
} elseif ( in_array( (string) $parent_obj['post_title'], $parent_array ) ) {
return true;
} elseif ( in_array( (string) $parent_obj['post_name'], $parent_array ) ) {
return true;
} else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment