I’m trying to delete all child posts when the parent is deleted.

The parent post deletes just fine, but the child posts are not properly deleting.

Here’s the code I have in place now:

$args = array( 
        'post_parent' => $parentid,
        'post_type' => 'custom-type'
    );

    $posts = get_posts( $args );

    if ($posts) {

        // Delete all the Children of the Parent Page
        foreach($posts as $post){

            wp_delete_post($post->ID, true);

        }

    }

    // Delete the Parent Page
    wp_delete_post($parentid, true);

What it should do is loop through and get the posts that are the child of $parentid and delete them, then delete the parent post.

Currently, it just deletes the parent post, but leaves all the children behind.

I’m looking at my database and the child pages are definitely created correctly with the correct post_parent id.

Is there a way to get all child posts and delete them?

Thanks,

Jason

2 Answers
2

Try it like this:

$args = array( 
    'post_parent' => $parentid,
    'post_type' => 'custom-type'
);

$posts = get_posts( $args );

if (is_array($posts) && count($posts) > 0) {

    // Delete all the Children of the Parent Page
    foreach($posts as $post){

        wp_delete_post($post->ID, true);

    }

}

// Delete the Parent Page
wp_delete_post($parentid, true);

Leave a Reply

Your email address will not be published. Required fields are marked *