Email Alert When Posts or Pages Are Trashed
Emails the site admin whenever a post or page is moved to the trash, with who did it and a link to restore it, so accidental or malicious deletions are spotted quickly.
Opens WPIDE on
Code
$wpide_trash_types = array( 'post', 'page' );
$wpide_trash_skip_admins = false;
add_action( 'wp_trash_post', function ( $post_id ) use ( $wpide_trash_types, $wpide_trash_skip_admins ) {
$post = get_post( $post_id );
if ( ! $post || ! in_array( $post->post_type, $wpide_trash_types, true ) || 'auto-draft' === $post->post_status ) {
return;
}
if ( $wpide_trash_skip_admins && current_user_can( 'manage_options' ) ) {
return;
}
$user = wp_get_current_user();
$who = $user->exists() ? $user->display_name . ' (' . $user->user_login . ')' : 'an automated process';
wp_mail(
get_option( 'admin_email' ),
sprintf( '[%s] "%s" was moved to the trash', wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ), wp_strip_all_tags( get_the_title( $post ) ) ),
sprintf( "The %s \"%s\" was trashed by %s on %s.\n\nRestore it from the trash: %s", $post->post_type, wp_strip_all_tags( get_the_title( $post ) ), $who, wp_date( 'Y-m-d H:i' ), admin_url( 'edit.php?post_status=trash&post_type=' . $post->post_type ) )
);
} );
Notes
Limit the post types with the list at the top; trashing by administrators can be skipped with $wpide_trash_skip_admins.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.