Halloween Sale 15% off Ends in See the plans
PHP

Email Alert When a User Account Is Deleted

Emails the site admin when any user account is deleted, including who deleted it and whether their content was reassigned, so removals never go unnoticed.

Don’t have WPIDE yet? Install it on your site

Code

add_action( 'delete_user', function ( $user_id, $reassign = null ) {
    $user  = get_userdata( $user_id );
    $actor = wp_get_current_user();

    if ( ! $user ) {
        return;
    }

    $reassigned = $reassign ? get_userdata( (int) $reassign ) : false;

    wp_mail(
        get_option( 'admin_email' ),
        sprintf( '[%s] User deleted: %s', wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ), $user->user_login ),
        sprintf(
            "The account %s <%s> (%s) was deleted by %s on %s.\nContent: %s",
            $user->user_login,
            $user->user_email,
            implode( ', ', (array) $user->roles ),
            $actor->exists() ? $actor->user_login : 'an automated process',
            wp_date( 'Y-m-d H:i' ),
            $reassigned ? 'reassigned to ' . $reassigned->user_login : 'deleted with the account'
        )
    );
}, 10, 2 );

Notes

Works for single sites; on multisite network user deletions use a different hook.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.