I am trying to recursively get all children of a page (infinite depth) and I am using function below, from this solution:

function get_all_subpages($page, $args = '', $output = OBJECT) {
    if (! is_numeric($page))
        $page = 0;

    $default_args = array(
        'post_type' => 'page',
    if (empty($args))
        $args = array();
    elseif (! is_array($args))
        if (is_string($args))
            parse_str($args, $args);
            $args = array();
    $args = array_merge($default_args, $args);
    $args['post_parent'] = $page;

    $valid_output = array(OBJECT, ARRAY_A, ARRAY_N);
    if (! in_array($output, $valid_output))
        $output = OBJECT;

    $subpages = array();
    $children = get_children($args, $output);
    foreach ($children as $child) {
        $subpages[] = $child;

        if (OBJECT === $output)
            $page = $child->ID;
        elseif (ARRAY_A === $output)
            $page = $child['ID'];
            $page = $child[0];

        $subpages = array_merge($subpages, get_all_subpages($page, $args, $output));

    return $subpages;

What would be the proper way in WordPress to iterate through the returned array so that I can use functions like get_permalink on sub-pages?


For the above function this would work:

$children = get_all_subpages($cat_id, $args, OBJECT);
foreach ($children as $post) { 
         echo $post->guid;
         echo $post->post_title;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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