Skip to content

Instantly share code, notes, and snippets.

@hirejordansmith
Last active June 1, 2021 23:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save hirejordansmith/cf12cbfa980e1340afd0 to your computer and use it in GitHub Desktop.
Save hirejordansmith/cf12cbfa980e1340afd0 to your computer and use it in GitHub Desktop.
How to check if page is parent or child or grandchild of a page
<?php
// Check for a specific page
if ( is_page(2) ) {
// stuff
}
// Check if page is child of a certain page
if ( $post->post_parent == '2' ) {
// stuff
}
// Is page a parent or child of the parent
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
};
// Is page a parent, child or any ancestor of the page
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;
}
};
// Usage
if (is_tree(2)) {
// stuff
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment