The ‘pre_trash_post’ WordPress PHP filter allows you to control whether a post should be trashed or not.
You can use this filter to add custom conditions before trashing a post.
Usage
apply_filters( 'pre_trash_post', $trash, $post );
Parameters
- $trash (bool|null): Whether to go forward with trashing the post.
- $post (WP_Post): The post object to be trashed.
Examples
Prevent trashing posts with specific tags
function prevent_trash_specific_tags( $trash, $post ) { // Check if the post has the tag "important" if ( has_tag( 'important', $post ) ) { return false; } return $trash; } add_filter( 'pre_trash_post', 'prevent_trash_specific_tags', 10, 2 );
In this example, we prevent posts with the “important” tag from being trashed. If a post has the “important” tag, the function returns false, and the post won’t be trashed.
Allow trashing only for draft posts
function trash_only_drafts( $trash, $post ) { // Check if the post is in draft status if ( 'draft' === $post->post_status ) { return true; } return false; } add_filter( 'pre_trash_post', 'trash_only_drafts', 10, 2 );
This example allows only draft posts to be trashed. If a post is not in draft status, it cannot be trashed.
Trash posts only by specific user role
function trash_posts_by_role( $trash, $post ) { $user = wp_get_current_user(); // Check if the current user has the "editor" role if ( in_array( 'editor', $user->roles ) ) { return true; } return false; } add_filter( 'pre_trash_post', 'trash_posts_by_role', 10, 2 );
In this example, we allow only users with the “editor” role to trash posts. If the current user is not an editor, the post won’t be trashed.
Trash posts older than a specific date
function trash_old_posts( $trash, $post ) { $post_date = strtotime( $post->post_date ); $cutoff_date = strtotime( '2023-01-01' ); // Check if the post date is older than the cutoff date if ( $post_date < $cutoff_date ) { return true; } return false; } add_filter( 'pre_trash_post', 'trash_old_posts', 10, 2 );
This example checks if a post is older than a specific date (January 1, 2023). If the post is older than the cutoff date, it can be trashed.
Allow trashing only for posts with a minimum number of comments
function trash_posts_with_min_comments( $trash, $post ) { $comment_count = wp_count_comments( $post->ID )->approved; // Check if the post has at least 5 approved comments if ( $comment_count >= 5 ) { return true; } return false; } add_filter( 'pre_trash_post', 'trash_posts_with_min_comments', 10, 2 );
In this example, we allow trashing posts only if they have a minimum of 5 approved comments. If a post has fewer than 5 approved comments, it cannot be trashed.