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 );
            }
        }
	}
 }