I have set up a custom post type, which user can edit from the frontend. I'm using wp_delete_post()
to allow users to delete a post they created. It works, but the posts get deleted instead of being moved to trash.
I have tried moving a post to the bin via the backend and it works like you would expect it, the post is moved to the Bin. So I'm not sure why the wp_delete_post
doesn't work the same way, but permanently removes the post instead.
According to the WordPress Codex, the second parameter of the wp_delete_post()
function is a boolean, which, if set to false, should move the post to trash, not permanently delete it. The second parameter is set to false by default, so this is my code:
wp_delete_post( $race->ID );
I'm aware that I can use the wp_trash_post()
function instead (which is actually what I'm using now, since the wp_delete_post
, doesn't do what I want it to do), but I would like to find out why the wp_delete_post()
function doesn't work correctly.
I have set up a custom post type, which user can edit from the frontend. I'm using wp_delete_post()
to allow users to delete a post they created. It works, but the posts get deleted instead of being moved to trash.
I have tried moving a post to the bin via the backend and it works like you would expect it, the post is moved to the Bin. So I'm not sure why the wp_delete_post
doesn't work the same way, but permanently removes the post instead.
According to the WordPress Codex, the second parameter of the wp_delete_post()
function is a boolean, which, if set to false, should move the post to trash, not permanently delete it. The second parameter is set to false by default, so this is my code:
wp_delete_post( $race->ID );
I'm aware that I can use the wp_trash_post()
function instead (which is actually what I'm using now, since the wp_delete_post
, doesn't do what I want it to do), but I would like to find out why the wp_delete_post()
function doesn't work correctly.
2 Answers
Reset to default 6Following the line of code
https://core.trac.wordpress/browser/tags/4.9/src/wp-includes/post.php#L2467
if ( ! $force_delete && ( 'post' === $post->post_type || 'page' === $post->post_type ) && 'trash' !== get_post_status( $postid ) && EMPTY_TRASH_DAYS ) {
return wp_trash_post( $postid );
}
the $force_delete just work with 'post' and 'page', it not work with custom post type
The wp_delete_post()
has pre_delete_post
filter before the deletion takes place, which you can use to prevent custom post types from getting deleted.
function prevent_cpt_delete( $delete, $post, $force_delete ) {
// Is it my post type someone is trying to delete?
if ( 'my_post_type' === $post->post_type && ! $force_delete ) {
// Try to trash the cpt instead
return wp_trash_post( $post->ID ); // returns (WP_Post|false|null) Post data on success, false or null on failure.
}
return $delete;
}
add_filter('pre_delete_post', 'prevent_cpt_delete', 10, 3);