Samik Chattopadhyay
Samik Chattopadhyay

Reputation: 1850

How to get all child pages of a page by the parent page title in Wordpress?

Example :

About
--- technical
--- medical
--- historical
--- geographical
--- political

how to create a function like this ?

function get_child_pages_by_parent_title($title)
{
    // the code goes here
}

and calling it like this which will return me an array full of objects.

$children = get_child_pages_by_parent_title('About');

Upvotes: 3

Views: 22885

Answers (3)

janw
janw

Reputation: 6662

You can use this, it does work on page ID rather then title, if you really need page title, I can fix it, but ID is more stable.

<?php
function get_child_pages_by_parent_title($pageId,$limit = -1)
{
    // needed to use $post
    global $post;
    // used to store the result
    $pages = array();

    // What to select
    $args = array(
        'post_type' => 'page',
        'post_parent' => $pageId,
        'posts_per_page' => $limit
    );
    $the_query = new WP_Query( $args );

    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        $pages[] = $post;
    }
    wp_reset_postdata();
    return $pages;
}
$result = get_child_pages_by_parent_title(12);
?>

It's all documented here:
http://codex.wordpress.org/Class_Reference/WP_Query

Upvotes: 11

Denis V
Denis V

Reputation: 3370

Why not to use get_children()? (once it's considered to use ID instead of the title)

$posts = get_children(array(
    'post_parent' => $post->ID,
    'post_type' => 'page',
    'post_status' => 'publish',
));

Check the official documentation.

Upvotes: 6

Simon
Simon

Reputation: 3717

I would prefer doing this without WP_Query. While it might not be any more efficient, at least you'd save yourself some time not having to write all those while/have_posts()/the_post() statements yet another time.

function page_children($parent_id, $limit = -1) {
    return get_posts(array(
        'post_type' => 'page',
        'post_parent' => $parent_id,
        'posts_per_page' => $limit
    ));
}

Upvotes: 8

Related Questions