Reputation: 1850
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
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
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
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