Halloween Sale 15% off Ends in See the plans
PHP

Email Alerts When Application Passwords Are Created

Emails the user and the site administrator whenever a new application password is created for an account, since these passwords give API access that bypasses the normal login.

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

Code

add_action( 'wp_create_application_password', function ( $user_id, $item ) {
    $user = get_userdata( $user_id );

    if ( ! $user ) {
        return;
    }

    $site    = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
    $actor   = wp_get_current_user();
    $message = sprintf(
        "A new application password named \"%s\" was created for the account %s.\n\nCreated by: %s\nIP address: %s\nTime: %s\n\nIf this was not expected, revoke it under Users > Profile > Application Passwords and change the account password.",
        isset( $item['name'] ) ? $item['name'] : '',
        $user->user_login,
        $actor->exists() ? $actor->user_login : 'unknown',
        isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
        wp_date( 'Y-m-d H:i' )
    );

    $recipients = array_unique( array( $user->user_email, get_option( 'admin_email' ) ) );
    wp_mail( $recipients, sprintf( '[%s] New application password', $site ), $message );
}, 10, 2 );

Notes

Application passwords created by the user themselves also trigger the email, which doubles as a receipt.

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.