Wordpress php: Way to test if pages are children of a parent page?


Working on my first Wordpress site so I'm sure this is a really basic question. I'm struggling to write a conditional php statement that performs a certain action when a page is a child of a parent page.

For example, rather than just specifying one page, as below, I'd like to specify all pages that have the 'About Us' page as a parent:

<?php if (is_page('About Us')) echo 'Hello World!'; ?>

I've tried the "child_of" function but it wasn't as straightforward as I'd hoped.

When I use the below, I get a syntax error - probably just me not knowing how to use the function:

<?php if (child_of('About Us')) echo 'Hello World!'; ?>

Any suggestions?


Simple solution where you want to link to the parent page from the child page; $post->post_parent holds the ID of a page's parent if there is one or it is zero if there is not one:

if($post->post_parent !== 0){               
    print '<a href="'.get_permalink($post->post_parent).'">&larr; Back</a>';    

so for this case you would want to change the if() to check if $post->post_parent == $id_of_about_page.

By : Duncanmoo

This code solved the problem for me guys, incase any one is wondering for a alernative:

    global $post;
    if ($post->post_parent == 9) {

        echo 'blah blah';

}; ?>

"9" is the id of the parent page.

Add the following function to your functions.php theme file:

function is_tree($pid) {      // $pid = The ID of the page we're looking for pages underneath
    global $post;         // load details about this page
    $anc = get_post_ancestors( $post->ID );
    foreach($anc as $ancestor) {
        if(is_page() && $ancestor == $pid) {
            return true;
               return true;   // we're at the page or at a sub page
               return false;  // we're elsewhere

Then you can use the following:

if(is_tree('2')){ // 2 being the parent page id
   // Do something if the parent page of the current page has the id of two

Reference: http://codex.wordpress.org/Conditional_Tags

This video can help you solving your question :)
By: admin