0

I'm trying to create a page which display a few of sub pages (child pages), however if the page has not child I would like to display a message.

I cannot get a query that allow me to do something like this:

 if (Page has childs) {
    do this
 }
 else {
    display this
 }

Any help?

Thanks in advanced

  • I accept em all the time, I haven't had the time to check this specific since I didn't spect to get the answer so fast and is friday night so basically will be a few hours until I get in my computer again, also I saw u gave me an answer, I'd appreciated your time, and will be happy to give you the points later, Regards – andresmijares Jan 20 '12 at 23:16
  • Oh that's alright, was just a friendly reminder. Just trying to do the best I can to contribute here! :) – Jared Jan 20 '12 at 23:30
2
$args = array(
    'post_status' => 'publish',
    'post_parent' => $post_id
);
$children = get_posts( $args );

if( count( $children ) > 0 ) {
    //has children
} else {
    //does not have children
}

Docs: get_posts()

This should also allow you to have access to the data of the children, should you need it. If you need any additional parameters in $args (a post type, for example), make sure to include those.

1

What about using something like this (provided you have a way to get the ID of the page you are checking for child pages):

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

However if you want to get just direct descendants, see m0r7if3r's, or this would also work too:

$children = get_pages( array( 'child_of' => $post->ID, 'parent' => 0 ) );

And then check that using count($children) with an if statement like so:

if( count( $children ) > 0 ) {
    // has children (and grandchildren if not using the 'parent' param)
} else {
    // does not have children
}
  • 1
    Could use a few more args, but I like the way you think ;) – mor7ifer Jan 20 '12 at 22:30
  • Yeah definitely lol, this will also grab the grandchildren of the page if any, 'parent' => 0 would be more suitable if he's just looking for direct descendants along with the child_of parameter. – Jared Jan 20 '12 at 22:35

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.