Check if post has children or not

I need some code to know if the post has another pages or not

unfortunately i didn’t find yet now any reference for this so any idea will be appreciated

What I need to acheive is

if has child 

//some staff 

else: 
// another staff

now I am using

$args = array(
'post_parent' => get_the_ID(), // Current post's ID
);
$children = get_children( $args );
// Check if the post has any child
if ( ! empty($children) ) {
// The post has at least one child

echo 'yes';
} else {
// There is no child for this post

echo 'no';
}

but any post have featured img returning yes and if used post_type=post in args all posts returned no even if have child

1 Answer
1

You can first attempt and get a list of post’s children. If the returned value was empty, then the post has no child. Here’s how you do it:

$args = array(
    'post_parent' => get_the_ID(), // Current post's ID
);
$children = get_children( $args );
// Check if the post has any child
if ( ! empty($children) ) {
    // The post has at least one child
} else {
    // There is no child for this post
}

Leave a Comment