Using WordPress ‘check_password’ PHP filter

The check_password WordPress PHP filter allows you to filter whether the plaintext password matches the encrypted password.

Usage

add_filter('check_password', 'your_custom_function', 10, 4);

function your_custom_function($check, $password, $hash, $user_id) {
  // your custom code here
  return $check;
}

Parameters

  • $check (bool) – Whether the passwords match.
  • $password (string) – The plaintext password.
  • $hash (string) – The hashed password.
  • $user_id (string|int) – User ID. Can be empty.

More information

See WordPress Developer Resources: check_password

Examples

Add custom password validation

Add a custom password validation check that requires the first character to be an uppercase letter.

add_filter('check_password', 'custom_password_validation', 10, 4);

function custom_password_validation($check, $password, $hash, $user_id) {
  if (ctype_upper(substr($password, 0, 1))) {
    return $check;
  } else {
    return false;
  }
}

Log failed password attempts

Log failed password attempts to a file for security purposes.

add_filter('check_password', 'log_failed_password_attempts', 10, 4);

function log_failed_password_attempts($check, $password, $hash, $user_id) {
  if (!$check) {
    $log = 'Failed login attempt for user ID: ' . $user_id . ' on ' . date('Y-m-d H:i:s') . "\n";
    file_put_contents('failed_logins.log', $log, FILE_APPEND);
  }
  return $check;
}

Disable password check for a specific user

Disable the password check for a specific user (e.g. user ID 5) for testing purposes.

add_filter('check_password', 'disable_password_check_for_user', 10, 4);

function disable_password_check_for_user($check, $password, $hash, $user_id) {
  if ($user_id == 5) {
    return true;
  }
  return $check;
}

Require a minimum password length

Enforce a minimum password length of 8 characters.

add_filter('check_password', 'require_min_password_length', 10, 4);

function require_min_password_length($check, $password, $hash, $user_id) {
  if (strlen($password) >= 8) {
    return $check;
  } else {
    return false;
  }
}

Add a custom password hashing algorithm

Use a custom password hashing algorithm instead of the default WordPress hashing.

add_filter('check_password', 'custom_password_hashing', 10, 4);

function custom_password_hashing($check, $password, $hash, $user_id) {
  $custom_hash = your_custom_hash_function($password);
  return ($custom_hash == $hash);
}