0

I need to disable the permanent deletion of posts (it's ok to trash them, but users shouldn't be able to delete them from trash).

I did that by hooking into before_delete_post and redirecting (thanks to this thread):

function disable_delete_post() {
    wp_redirect(admin_url('edit.php'));
    exit();
} 
add_action('before_delete_post', 'disable_delete_post', 1);

This works, however, users report that sometimes (not clear when) they are redirected when they're trying to open the editor of a (published) post, which prevents the post from being edited at all.

So it seems the function is executed even though the user is not trying to delete (in fact, I'm also hiding the "delete permanently" link via CSS, so users shouldn't be able to trigger this in the first place).

Does anybody have any ideas why before_delete_posts might run outside of post deletion?

Hiding the link via CSS is not enough as a solution, it needs to be more secure (someone with CSS skills could circumvent it).

** Alternative Solution I'm considering: **

Adding a conditional to check for post status and only redirect when status of post is 'trash':

function disable_delete_post($old_status) {
  if ($old_status = 'trash' ) {
     wp_redirect(admin_url('edit.php'));
     exit();
  }
} 
add_action('before_delete_post', 'disable_delete_post', 1);

I'm hoping this fixes the problem but because I don't understand the root I'm hesitant to use this on a live site.

2
  • which editor are you referring to? There are lots of kinds of posts not just "Post", this could even be autodrafts, revisions, or something unrelated to the editor e.g. part of a 3rd party plugin. The docs for that action don't include an old status in the parameters, it isn't safe to guess these things, developer.wordpress.org/reference/hooks/before_delete_post you should collect more information first, check the post ID and post objects for clues. Also why not ask how to prevent users from deleting posts? That question has a much easier answer that has nothing to do with this filter
    – Tom J Nowell
    Commented May 4, 2023 at 10:32
  • Thank you, this is helpful. You're right, I'll ask that other question instead.
    – user232080
    Commented May 8, 2023 at 7:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.