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

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', 'pse_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', 'pse_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', 'pse_283736_pre_user_loginr_filter', 10, 3);

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

Hope it helps you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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