clean_user_cache()WP 3.0.0

Clean all user caches

1 time — 0.000052 sec (very fast) | 50000 times — 8 sec (fast) | PHP 7.0.2, WP 4.4.2
Hooks from the function

Return

null. Nothing (null).

Usage

clean_user_cache( $user );
$user(WP_User|int) (required)
User object or ID to be cleaned from the cache

Examples

0

#1 Cleaning the user cache

Suppose we update a user and in the process of updating we changed his data, for example, by a separate query in the database. Now the current data may not match the data we get from the cache using get_userdata() or from the data in the global variable $current_user.

To update all this data, you need to completely clear the user's cache:

$user_id = 12;
clean_user_cache( $user_id );

Changelog

Since 3.0.0 Introduced.
Since 4.4.0 clean_user_cache was added.
Since 6.2.0 User metadata caches are now cleared.

clean_user_cache() code WP 6.7.1

function clean_user_cache( $user ) {
	if ( is_numeric( $user ) ) {
		$user = new WP_User( $user );
	}

	if ( ! $user->exists() ) {
		return;
	}

	wp_cache_delete( $user->ID, 'users' );
	wp_cache_delete( $user->user_login, 'userlogins' );
	wp_cache_delete( $user->user_nicename, 'userslugs' );

	if ( ! empty( $user->user_email ) ) {
		wp_cache_delete( $user->user_email, 'useremail' );
	}

	wp_cache_delete( $user->ID, 'user_meta' );
	wp_cache_set_users_last_changed();

	/**
	 * Fires immediately after the given user's cache is cleaned.
	 *
	 * @since 4.4.0
	 *
	 * @param int     $user_id User ID.
	 * @param WP_User $user    User object.
	 */
	do_action( 'clean_user_cache', $user->ID, $user );
}