wp_delete_user with username

wp_delete_user() function requires user ID and [optional] reassign ID if the content is to be reassigned to another user.

All users’ user names are also unique as WP doesn’t allow duplicate user names. If I know username, is there no way with just one PHP/mysqli query I can delete the user instead of run one query to find ID of that user first and then tell wordpress to delete that user ?

2 Answers
2

There is no way to do this with only one query. But to be honest – deleting user takes more than one query itself…

You shouldn’t use custom SQL for that, because there are many things you could break this way… Always use WP functions, if they exists (what if some plugin logs every deleted user, or what if some other action is needed, etc.)

You can use get_user_by to achieve that. Here’s the example:

$user = get_user_by( 'login', 'john' );
if ( $user ) { // get_user_by can return false, if no such user exists
    wp_delete_user( $user->ID );
}

The fields you can get user by are: ID | slug | email | login.

Leave a Comment