How to get all child pages of a page by the parent

2019-04-02 02:35发布

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');

标签: wordpress
3条回答
Bombasti
2楼-- · 2019-04-02 02:36

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.

查看更多
太酷不给撩
3楼-- · 2019-04-02 02:44

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
    ));
}
查看更多
再贱就再见
4楼-- · 2019-04-02 02:51

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

查看更多
登录 后发表回答