Check if a Page is a Child of Another Page in WordPress

Posted on November 20, 2009  |  Category: Tutorials

WordPressWordPress has some default conditional tags that are really helpful when developing themes and plugins that need specific functions on specific pages. Strange enough though, there is no way to check if a page is a child of another page.

This small function checks the database to see if the page happens to have a parent page assigned to it. If so, then the function will return true.

function is_child($pageID) { 
	global $post; 
	if( is_page() && ($post->post_parent==$pageID) ) {
               return true;
	} else { 
               return false; 
	}
}

Place the above code in your theme’s functions.php file, or create a functions.php file and place it in your theme’s directory. Then you can use the is_child() function anywhere in your theme. Your code would look something like this:

<?php
if(is_child(343)) {
echo "This is a child page of 'The Parent Page Title'.";
}
?>

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , ,

Short URL: http://bavotasan.com/?p=1456

Leave a Reply

To enter code in the comment box, please place it between <pre lang="php"> </pre> tags. You don't have to convert any characters to their hex/HTML code. Just add your code the way you would to any code editor.