Hello! 欢迎来到盒子萌!

wordpress前端用户中心类开发的一些常用函数功能笔记


NOTE:WordPress 支持中文用户名
//让wordpress支持中文用户名
function ludou_sanitize_user ($username, $raw_username, $strict) {
  $username = wp_strip_all_tags( $raw_username );
  $username = remove_accents( $username );
  // Kill octets
  $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
  $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
  // 网上很多教程都是直接将$strict赋值false,
  // 这样会绕过字符串检查,留下隐患
  if ($strict) {
    $username = preg_replace ('|[^a-z\p{Han}0-9 _.\-@]|iu', '', $username);
  }
  $username = trim( $username );
  // Consolidate contiguous whitespace
  $username = preg_replace( '|\s+|', ' ', $username );
  return $username;
}
add_filter ('sanitize_user', 'ludou_sanitize_user', 10, 3);
NOTE:非管理员不允许进入后台
//非管理员不允许进入后台
if ( is_admin() && ( !defined( 'DOING_AJAX' ) || !DOING_AJAX ) ) {
  $current_user = wp_get_current_user();
  if($current_user->roles[0] == get_option('default_role')) {
    wp_safe_redirect( home_url() );
    exit();
  }
}
NOTE:WordPress 支持Email登录
// 修改WordPress用户名过滤机制,通过Email获取用户名
function ludou_allow_email_login($username, $raw_username, $strict) {
  if (filter_var($raw_username, FILTER_VALIDATE_EMAIL)) {
    $user_data = get_user_by('email', $raw_username);
    if (empty($user_data))
      wp_die(__('<strong>ERROR</strong>: There is no user registered with that email address.'), '用户名不正确');
    else
      return $user_data->user_login;
  }
  else {
    return $username;
  }
}
if (strpos($_SERVER['REQUEST_URI'], '?action=register') === FALSE && strpos($_SERVER['REQUEST_URI'], '?action=lostpassword') === FALSE && strpos($_SERVER['REQUEST_URI'], '?action=rp') === FALSE ) {
  add_filter('sanitize_user', 'ludou_allow_email_login', 10, 3);
}

暂无评论

发表评论

相关阅读