Nov
20
2009

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


WordPress 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'.";
}
?>
If you liked this, please share it.

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

Short URL: http://bit.ly/c4pYxR

Discussion 3 Comments

  1. Matt Cassarino on February 26, 2010 at 12:26 pm

    This rocks, thanks a lot!

    • el loco on August 2, 2010 at 1:50 am

      muy bueno exelente!!

  2. Acai on April 19, 2010 at 8:54 am

    It’s great to know your way around WordPress. I love it! Even if you do have to do some things in a roundabout way.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


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.