1

I am watching a wordpress tutorial on Youtube about get_pages() and "child_of":

(from 17'28" to 18'35") https://www.youtube.com/watch?v=GHTZn3atTcM

To check with a page has child(ren) or not, he suggested to use get_pages() with "child_of" to check it. So I created the following category stucture:

About Us

- Sub about us // child of about us

Contact Us // with no child(ren)

There is 1 post for each category.

And then I put the following into the single.php to check:

$array = get_pages('child_of=' . $post->ID);

echo count($array);

Supposed that "About Us" should return 1 as it has a child.

While for "Sub about us" and "Contact Us" should return 0 as both have no child.

But at the end all are returning 0, may I know what am I doing wrong?

Am I misunderstanding how to use get_pages() & "child_of"?

Thanks very much!

1

1 Answer 1

0

You are using it at wrong place, You can use the same function in page.php and if you want to use it in single.php then you have to pass static pageId as parameters.

Right now you are passing $post->ID which will return post id of current article and Articles does not have any relation with pages.

 $defaults = array(
    'depth'        => 0,
    'show_date'    => '',
    'date_format'  => get_option( 'date_format' ),
    'child_of'     => 0,
    'exclude'      => '',
    'title_li'     => __( 'Pages' ),
    'echo'         => 1,
    'authors'      => '',
    'sort_column'  => 'menu_order, post_title',
    'link_before'  => '',
    'link_after'   => '',
    'item_spacing' => 'preserve',
    'walker'       => '',
);

$r = wp_parse_args( $args, $defaults );

Above code will return all the pages, Now if you want to get child of about us then pass PageID of about us in 'child_of' => 0 parameter. It will return only child of about us.

Another thing, You can get child pages of current page using following function.

$mypages = get_pages( array( 'child_of' => $post->ID, 'sort_column' => 'post_date', 'sort_order' => 'desc' ) );

Here you need to write this code in page.php or any page template then it will return the child pages of current page.

Let me know if you find an issue.

2
  • 1
    Thank you very very much Sudhir, you have no idea how much I appreciate you. Have a nice day!
    – Kenny
    Commented Jun 22, 2017 at 21:58
  • You are welcome Kenny. Have a great day! Commented Jun 23, 2017 at 7:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.