Skip to content

Instantly share code, notes, and snippets.

@iftee
Last active June 14, 2016 10:04
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 iftee/cf893030ae06f3b91cf6737f8c60e537 to your computer and use it in GitHub Desktop.
Save iftee/cf893030ae06f3b91cf6737f8c60e537 to your computer and use it in GitHub Desktop.
WordPress: Function to check if current page is a direct child to another page
<?php
/*
* Check if the current pae is a direct child of another page.
* Accept's page ID, page slug or page title as parameters to identify the parent.
*/
/* Add the following code in the theme's functions.php */
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;
}
}
/* Usage:
- with parent page ID: is_child( 101 )
- with parent page title: is_child( 'About Us' )
- with parent page slug: is_child( 'about-us' )
* Example:
if ( is_child( 'About Us' ) ) {
echo "This page is a direct child of About Us page";
}
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment