记录一些常用的函数和瞎折腾的过程……

更改wordress作者页面中的用户名为ID

提醒:本文最后更新于 2380 天前,文中所描述的信息可能已发生改变,请谨慎使用。

今天查看日志,竟然看到有人异常访问,连续使用/?author=1、/?author=2、/?author=3……进行尝试,我自己也试了下,竟然可以跳转到/author/username的网址,后台登录名给暴出来了啊!感觉问题有点大,立即百度查找解决方法,网上介绍了几个方法,如配置Rewrite、函数替换等。

我使用了一个函数替换的方法,在用/?author=1访问时,跳转为/author/user_id,而不是/author/username,这样感觉安全了点。这个要使用2个函数,第一个进行user_id和username的替换,第二个进行url重写,防止/author/user_id访问时出现404错误。

关于author的一些常用函数,可以参阅:https://codex.wordpress.org/Function_Reference/the_author_posts_link

    /**********屏蔽用/?author=1来获取登录名**********/
    /*
     * 修改重写作者存档页url
     * 屏蔽用/?author=1来获取author/username
     * 通过author/id来显示避免暴露登录名
     */
    add_filter( 'author_link', 'psay_author_link', 10, 2 );
    function psay_author_link( $link, $author_id) {
        global $wp_rewrite;
        $author_id = (int) $author_id;
        $link = $wp_rewrite->get_author_permastruct();
        if ( empty($link) ) {
            $file = home_url( '/' );
            $link = $file . '?author=' . $author_id;
        } else {
            $link = str_replace('%author%', $author_id, $link);
            $link = home_url( user_trailingslashit( $link ) );
        }
        return $link;
    }
    /**********author/id形式的URL重写避免404**********/
    /**
     * 上述function psay_author_link隐藏登录名后
     * 作者存档页链接有2个查询变量,
     * 系统默认使用author_name(作者用户名)来url重写
     * 改成author(作者用户id)后,没有进行url重写,访问author/id会404
     * 此处做的是,在url重写之后,把author_name替换为author,就可以正常访问author/id
     * @原文link https://www.wpdaxue.com/use-nickname-for-author-slug.html
     */
    add_filter( 'request', 'psay_author_link_request' );
    function psay_author_link_request( $query_vars ) {
        if ( array_key_exists( 'author_name', $query_vars ) ) {
            global $wpdb;
            $author_id=$query_vars['author_name'];
            if ( $author_id ) {
                $query_vars['author'] = $author_id;
                unset( $query_vars['author_name'] );
            }
        }
        return $query_vars;
    }