## Deleting CPT post by code (ie in a plugin) redirects to the main post type

Question

1. Suppose a CPT
2. In functions.php or in a plugin, hook on ‘save_post’ to perform some
calculations upon hitting the Publish button in WP-Admin…
3. Inside the hook’s code include some conditional logic that under
certain circumstances it will delete the CPT post that is just being
created. Ie study the following piece of code:
add_action('save_post', 'import_external_data', 10, 2);
function import_external_data($post_id,$post)
{
if ($post->post_status == 'publish' &&$post->post_type == 'movie') {
// Check if movie exists
$movies = get_posts(array( 'numberposts' => 1, 'post_status' => 'publish', 'post_type' => 'movie', 'meta_key' => 'movie_id', 'meta_value' =>$post->post_content,
))[0];

if (empty($movies)) { // Various actions take place here } else { wp_delete_post($post_id, true);
}
}
}

1. Once the post is deleted you are redirected to the stock post type
(?post_type=<CPT_slug> part of the URL is gone)

I already reported this in WordPress’s bug tracker, but I wonder if it’s really a bug or if I’m doing something wrong…

0
2 months 2021-06-05T13:59:06-05:00 0 Answers 0 views 0