Error after deleting Custom Post Type with a function (no trash used)

I’m using a function which I built to delete all posts from a user after a specific post is deleted. In my case I’m using a Custom Post Type called company. And additional Custom Post Types like jobs or events. If the company profile gets deleted, all other posts from this user are also deleted.

My problem now: If I do this for normal posts, the posts are moved to the trash.
Everything ok here…

But if I do this for the other Custom Post Types, they are deleted complitly without trash. I could trash them if I delete them in the admin area. So the trash is active!?

Any ideas whats going wrong? Here is my code:

function delete_all_posts_from_author($post_id) {


    global $post;
    $id = $post->ID;

    // Only trigger if post type is "company"
    if ( get_post_type($id) == "company" ) {

        $author_id = $post->post_author;

        $posts_from_author = get_posts(
            array(
                'posts_per_page'    => -1,
                'post_status'       => 'publish',
                'post_type'         => array('event','job'),
                'author'            => $author_id,
                'fields'            => 'ids', // Only get post ID's
            )
        );

        foreach ( $posts_from_author as $post_from_author ) {
            wp_delete_post( $post_from_author, false); // Set to False if you want to send them to Trash.
        }
    }


}

add_action( 'publish_to_trash',  'delete_all_posts_from_author', 10, 1 );

1 Answer
1

From looking at the source quite curiously $force_delete argument in wp_delete_post() only applies to native posts, pages, and attachments.

My quick guess would be that for CPTs you would need to use explicit wp_trash_post() function if you want trash behavior.

Leave a Comment