[+] Automatically delete child posts when parent is deleted

The following is intended to work with relationships created with Types 3+. Edit the code to include the slug of the parent post type, and the slug of the relationship. When a parent post is deleted, its children will be deleted, too.

/**
 * Automatically delete child posts when deleting a parent
 */
 add_action( 'before_delete_post', 'ts_delete_children', 9, 2 );
 function ts_delete_children( $post_id, $post ){

	$parent_type = 'book'; // Edit parent post type slug
	$relationship_slug = 'book-chapter'; // Edit relationship slug

	if ( $post->post_type === $parent_type ){
		$children = toolset_get_related_posts( $post_id, $relationship_slug, ['query_by_role' => 'parent','role_to_return' => 'child','args' => ['post_status' => [ 'publish', 'trash' ] ] ] );

        if ( is_array( $children ) )
        {
            foreach ($children as  $child)
            {
                wp_delete_post( $child );
            }
        }
	}
 }

Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments