0

I have a WooCommerce module creating Wordpress usernames on my behalf. I want to make sure those usernames are sanitized according to my rules, which are stricter than the Wordpress requirements.

How can I hook / override sanitize_user to use my custom rules?

1 Answer 1

1

sanitize_user function has a sanitize_user filter. The filter gives you $username, $raw_username, $strict from the sanitize_user and expects you to return $username, according to the inline documentation:

/**
* Filters a sanitized username string.
*
* @since 2.0.1
*
* @param string $username     Sanitized username.
* @param string $raw_username The username prior to sanitization.
* @param bool   $strict       Whether to limit the sanitization to specific characters. Default false.
*/

You would do something like:

function wpse_283736_sanitize_user_filter($username){
    // do your sanitization with $username
    return $username;
}
add_filter('sanitize_user', 'wpse_283736_sanitize_user_filter');

Or like this

function wpse_283736_sanitize_user_filter($username, $raw_username, $strict){
    // do your sanitization with $username or maybe $raw_username
    return $username; // or return $raw_username;
}
add_filter('sanitize_user', 'wpse_283736_sanitize_user_filter', 10, 3);

You could hook to pre_user_login filter, available on wp_insert_user function, which is used by Woocommerce user registration process.

$pre_user_login = apply_filters( 'pre_user_login', $sanitized_user_login );

function wpse_283736_pre_user_login_filter($sanitized_user_login){
    // do your sanitization with $sanitized_user_login
    return $sanitized_user_login;
}
add_filter('pre_user_login', 'wpse_283736_pre_user_login_filter', 10, 3);

If you are not familiar with WordPress Filters, I suggest you read these references first:

Hope it helps you.

2
  • 1
    This worked for me once fixing the epic function name spelling errors.
    – cbyte
    Commented Jul 26, 2021 at 0:31
  • wow, thanks for pointing it out. It took almost 4 years to someone to notice and point it. I am sorry for the epic misspellings. Shame on me. Commented Nov 2, 2021 at 17:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.