-
-
Save ericrasch/4723316 to your computer and use it in GitHub Desktop.
/* =BEGIN: Check If Page Is Child | |
Source: http://bavotasan.com/2011/is_child-conditional-function-for-wordpress/ | |
---------------------------------------------------------------------------------------------------- */ | |
function is_child( $page_id_or_slug ) { // $page_id_or_slug = The ID of the page we're looking for pages underneath | |
global $post; // load details about this page | |
if ( !is_numeric( $page_id_or_slug ) ) { // Used this code to change a slug to an ID, but had to change is_int to is_numeric for it to work. | |
$page = get_page_by_path( $page_id_or_slug ); | |
$page_id_or_slug = $page->ID; | |
} | |
if ( is_page() && ( $post->post_parent == $page_id_or_slug ) ) | |
return true; // we're at the page or at a sub page | |
else | |
return false; // we're elsewhere | |
}; |
/* =BEGIN: Check If Page Is Parent/Child/Ancestor | |
Source: http://css-tricks.com/snippets/wordpress/if-page-is-parent-or-child/#comment-172337 | |
---------------------------------------------------------------------------------------------------- */ | |
function is_tree( $page_id_or_slug ) { // $page_id_or_slug = The ID of the page we're looking for pages underneath | |
global $post; // load details about this page | |
if ( !is_numeric( $page_id_or_slug ) ) { // Used this code to change a slug to an ID, but had to change is_int to is_numeric for it to work: http://bavotasan.com/2011/is_child-conditional-function-for-wordpress/ | |
$page = get_page_by_path( $page_id_or_slug ); | |
$page_id_or_slug = $page->ID; | |
} | |
if ( is_page() && ( $post->post_parent == $page_id_or_slug || (is_page( $page_id_or_slug ) || in_array($page_id_or_slug, $post->ancestors) ) ) ) | |
return true; // we're at the page or at a sub page | |
else | |
return false; // we're elsewhere | |
}; |
To make the is_tree function in an is_child, just remove the last || is_page( $page_id_or_slug )
call. This will just the child pages of the parent and will not include the parent.
Found out is_tree was fully checking all the ancestors, fixed line 12 of is_tree.php (source: http://css-tricks.com/snippets/wordpress/if-page-is-parent-or-child/#comment-125480).
NOTE: If you want to use is_child
or is_tree
on child or subpages, you need to include the parent slug, too. Ex: is_tree( 'usa/texas' )
would cover /texas and /texas/houston.
You may want to consider adding a check to see if $page returns something; if it doesn't, it returns a vague error that's not easily to troubleshoot. (example https://gist.github.com/germanny/9399616#file-is_child-php-L10
)
error is:
Notice: Trying to get property of non-object in /vagrant/web/wp-content/themes/bc-theme/functions.php on line 178
If $page isn't set (such as if the page suddenly doesn't exist), then it just continues on gracefully.
Arrays like
is_tree('subpage1','subpage2','subpage3')
don't work. Wish it did.