skip to Main Content

For security reasons, I need to prevent users from permanently deleting posts from trash, while keeping the ability to trash posts and restore them from trash.

This code prevents users from permanently deleting drafts, but it also prevents them from restoring from trash:

add_filter ('user_has_cap', 'prevent_deletion', 10, 3);
 
function prevent_deletion ($allcaps, $caps, $args) {
    if (isset($args[0]) && isset($args[2]) && $args[0] == 'delete_post') {
        $post = get_post ($args[2]);
        if ($post->post_status == 'trash') {
            $allcaps[$caps[0]] = false;
        }
    }
    return $allcaps;
}

The if statement here is too broad (it prevents all actions with trashed posts, not just deleting), but I don’t know how to make it more specific. Or, if this is not the right path, what to do instead to achieve the goal.

Thanks!

2

Answers


  1. Chosen as BEST ANSWER

    I found a solution:

    function modify_pre_delete_post_defaults($delete, $post, $force_delete) { 
        return true; 
    }
    add_filter( "pre_delete_post", "modify_pre_delete_post_defaults", 10, 3 );
    

    See https://developer.wordpress.org/reference/hooks/pre_delete_post/


  2. edit in your wp-config.php file.

    define('EMPTY_TRASH_DAYS', 1 );
    

    //Integer is the amount of days

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search