WordPress注册账号支持中文的解决方案

追格官方小助手/ 2022年02月22日/ WordPress/ 浏览 1989

WordPress怎么支持中文注册,其实追格小编之前也没去尝试过去解决这个问题,今天趁有空研究了一下,不用WordPress插件即可轻松实现,方法很简单,将下面代码插入到当前主题functions.php中即可!


//WordPress支持中文名注册 追格 zhuige.com
function zhuige_sanitize_user ($username, $raw_username, $strict) {
$username = wp_strip_all_tags( $raw_username );
$username = remove_accents( $username );
$username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
$username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
if ($strict) {
$username = preg_replace ('|[^a-z\p{Han}0-9 _.\-@]|iu', '', $username);
}
$username = trim( $username );
$username = preg_replace( '|\s+|', ' ', $username );
return $username;
}
add_filter ('sanitize_user', 'zhuige_sanitize_user', 10, 3);


或者使用下面的代码也可以:


function zhuige_sanitize_user($username, $raw_username, $strict)
{
    if (!$strict)
        return $username;

    return sanitize_user(stripslashes($raw_username), false);
}
add_filter('sanitize_user', 'zhuige_sanitize_user', 10, 3);


其实,上面两段代码几乎无差别。只要看看 sanitize_user 函数的源码就知道了。


function sanitize_user( $username, $strict = false ) {
	$raw_username = $username;
	$username     = wp_strip_all_tags( $username );
	$username     = remove_accents( $username );
	// Kill octets.
	$username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
	// Kill entities.
	$username = preg_replace( '/&.+?;/', '', $username );

	// If strict, reduce to ASCII for max portability.
	if ( $strict ) {
		$username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
	}

	$username = trim( $username );
	// Consolidate contiguous whitespace.
	$username = preg_replace( '|\s+|', ' ', $username );

	/**
	 * 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.
	 */
	return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
}


当 $strict = false 执行的代码就是第一段代码。$strict 为 true 时,将禁止非 ASCII 字符,去掉这个限制就可以支持中文了。


发表评论

暂无评论,抢个沙发...

客服 工单