WordPress隐藏前台登录用户名

WordPress 鼠标点击前台用户名,浏览器就会跳转到 https://exploded.com/author/username 这个链接,这样一来就直接暴露了登陆用户名,哪怕你已经在前台使用了昵称。这是个很大的安全隐患!我不希望用户名和密码这两项中的任何一个暴露,但这样一来任何人都可以知道你的用户名了!

解决方案非常简单,只需要在 functions.php 中添加如下代码:

// 隐藏用户名
add_filter('author_link', function($link, $author_id, $author_nicename){
  $author	= get_userdata($author_id);
  
  if(sanitize_title($author->user_login) == $author_nicename){
    global $wp_rewrite;

    $link	= $wp_rewrite->get_author_permastruct();
    $link	= str_replace('%author%', $author_id, $link);
    $link	= home_url(user_trailingslashit($link));
  }
  return $link;
}, 10, 3);

最后把原链接直接 404 就好:

// 原作者页直接404
add_action('pre_get_posts',  function($wp_query) {
  if($wp_query->is_main_query() && $wp_query->is_author()){
    if($author_name = $wp_query->get('author_name')){
      $author_name	= sanitize_title_for_query($author_name);
      $author			= get_user_by('slug', $author_name);

      if($author){
        if(sanitize_title($author->user_login) == $author->user_nicename){
          $wp_query->set_404();
        }
      }else{
        if(is_numeric($author_name)){
          $wp_query->set('author_name', '');
          $wp_query->set('author', $author_name);
        }
      }
    }
  }
});

//修改body_class
add_filter('body_class', function($classes){
  if(is_author()){
    global $wp_query;

    $author	= $wp_query->get_queried_object();

    if(sanitize_title($author->user_login) == $author->user_nicename){
      $author_class	= 'author-'.sanitize_html_class($author->user_nicename, $author->ID);
      $classes		= array_diff($classes, [$author_class]);
    }
  }
  return $classes;
});

//修改comment_class
add_filter('comment_class', function ($classes){
  foreach($classes as $key => $class) {
    if(strstr($class, 'comment-author-')){
      unset($classes[$key]);
    }
  }
  return $classes;
});

 

邢森

感觉有被冒犯到

微信扫一扫

扫啊扫

微信扫一扫,分享到朋友圈

WordPress隐藏前台登录用户名
返回顶部