WordPress at Your Fingertips

Our Own Password for WordPress Application Password

Let's say we want to set the desired (defined, pre-known) password as the application password.

There is no suitable feature in WordPress to update the app password itself directly. Therefore, we will write our own function.

To set our password, first we need to create the application password data. To do this, create an application password. In this case, the password will be created automatically random. Perhaps you have already created a password for the app, then you can simply update it.

Now use this custom php function. Copy it, for example, to a theme's functions.php file:

/**
 * Update WordPress application password itself. Sets the password we specify.
 *
 * @param int    $user_id   ID of the user.
 * @param string $app_name  See the name on profile WP admin page.
 * @param array  $new_data {
 *     @type string $password Recommended format is: 'ukfU NAZ7 a5UG SV2s U8I2 ykkr'.
 *     @type string $app_id   ID of the application.
 *     @type string $name     New Application name.
 * }
 *
 * @return array|false
 */
function kama_update_application_password( $user_id, $app_name, $new_data ){

	$app_passwords = WP_Application_Passwords::get_user_application_passwords( $user_id );

	foreach( $app_passwords as & $data ){

		// skip - it's not our application password
		if( $app_name !== $data['name'] )
			continue;

		// set password
		$new_password = $new_data['password'];
		$new_password = preg_replace( '/[^a-z\d]/i', '', $new_password );
		$data['password'] = wp_hash_password( $new_password );

		// another data to change
		isset( $new_data['app_id'] ) && $data['app_id'] = $new_data['app_id'];
		isset( $new_data['name'] ) && $data['name'] = $new_data['name'];
	}
	unset( $data );

	// update application passwords in DB
	$done = update_user_meta( $user_id, WP_Application_Passwords::USERMETA_KEY_APPLICATION_PASSWORDS, $app_passwords );

	if( $done )
		return $app_passwords;

	return false;
}

Now call the function with the parameters we need, in which we specify the User ID, the name of the application for which we will update the password and the password itself:

$user_id = 10;
$app_name = 'Super App';
$new_data = [
	'password' => 'ukfU NAZ7 a5UG SV2s U8I2 ykkr',
];

$res = kama_update_application_password( $user_id, $app_name, $new_data );

print_r( $res );

/*
Array
(
	[0] => Array
		(
			[uuid] => e79943d7-0254-437c-b07a-70001bda4d32
			[app_id] => Super App
			[name] => Super App
			[password] => $P$BmG31CkQLJRmOPAiFXD0DCA9tTtmPY0
			[created] => 1608731275
			[last_used] => 1624346370
			[last_ip] => 208.88.226.229
		)

)
*/

The name of the application can get from the admin panel. Go to the profile of the user for whom you need to update the application password:

No comments
    Log In