Using WordPress ‘clean_user_cache’ PHP action

The clean_user_cache WordPress action is triggered immediately after the given user’s cache is cleaned.

Usage

add_action('clean_user_cache', 'your_custom_function', 10, 2);

function your_custom_function($user_id, $user) {
    // your custom code here
}

Parameters

  • $user_id (int): User ID.
  • $user (WP_User): User object.

More information

See WordPress Developer Resources: clean_user_cache

Examples

Log user cache cleaning

Log when a user’s cache is cleaned in a custom log file.

add_action('clean_user_cache', 'log_user_cache_clean', 10, 2);

function log_user_cache_clean($user_id, $user) {
    error_log("User cache cleaned for user ID: {$user_id}");
}

Send an email notification

Send an email notification to the admin when a user’s cache is cleaned.

add_action('clean_user_cache', 'notify_admin_user_cache_clean', 10, 2);

function notify_admin_user_cache_clean($user_id, $user) {
    $admin_email = get_option('admin_email');
    $subject = "User Cache Cleaned: {$user->user_login}";
    $message = "User cache cleaned for user: {$user->user_login} (ID: {$user_id})";
    wp_mail($admin_email, $subject, $message);
}

Update a custom user meta

Update a custom user meta field with the timestamp when the user’s cache is cleaned.

add_action('clean_user_cache', 'update_user_cache_clean_timestamp', 10, 2);

function update_user_cache_clean_timestamp($user_id, $user) {
    update_user_meta($user_id, 'cache_clean_timestamp', time());
}

Invalidate custom cache

Invalidate custom cache related to the user when their cache is cleaned.

add_action('clean_user_cache', 'invalidate_custom_user_cache', 10, 2);

function invalidate_custom_user_cache($user_id, $user) {
    // Invalidate custom cache for the user
}

Trigger third-party API

Trigger a third-party API when a user’s cache is cleaned.

add_action('clean_user_cache', 'trigger_third_party_api', 10, 2);

function trigger_third_party_api($user_id, $user) {
    // Call the third-party API with user data
}