'Wordpress create application password for user programmatically

First time working with Wordpress and looking to build a plugin.

In the plugin I create a user to which I want to create a named application password.

Is there a way to programmatically create this password? I cannot find an example of this.

I create my user like this within the Wordpress plugin:

        // create the user
        $user_id = wp_create_user(
            $this->plugin_wp_user_name,
            $this->plugin_wp_password_transient,
            $this->plugin_wp_user_email
        );

        $user = get_user_by('id', $user_id);

        $user_id = wp_update_user( array(
            'ID' => $user_id,
            'first_name' => 'API',
            'last_name' => 'User',
            'display_name' => 'API User',
            'description' => 'This user belongs to the App API. Please do not delete.',
            'user_url' => $this->plugin_owner_url,
        ) );


Solution 1:[1]

You can use the [WP_Application_Passwords::create_new_application_password( int $user_id, array $args = array() )][1].

Example code:

$user_id = get_current_user_id();
$app_exists = WP_Application_Passwords::application_name_exists_for_user( $user_id, 'your-app-name' );
 
if ( ! $app_exists ) {
    $app_pass = WP_Application_Passwords::create_new_application_password( $user_id, array( 'name' => 'your-app-name' ) );
}

Return (array|WP_Error) The first key in the array is the new password, the second is its detailed information. A WP_Error instance is returned on error.

Solution 2:[2]

I found it is the WordPress docs.

$app_password = \WP_Application_Passwords::create_new_application_password($user_id, $app_name);

The password is then retrieved from $app_password[0]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DharmanBot
Solution 2 TheRealPapa