默認情況下,修改固定鏈接為非默認帶?的樣式以後,作者存檔的鏈接一般為 http://域名/author/用戶名,這樣就直接暴露瞭登錄WordPress的用戶名,存在安全隱患。一個不錯的解決方法是將WordPress作者存檔鏈接中的用戶名改為昵稱。
將下面的代碼添加到當前主題的 functions.php 中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
/** * 將WordPress作者存檔鏈接中的用戶名改為昵稱 * https://www.wpdaxue.com/use-nickname-for-author-slug.html */ //使用昵稱替換用戶名,通過用戶ID進行查詢 add_filter( 'request', 'wpdaxue_request' ); function wpdaxue_request( $query_vars ) { if ( array_key_exists( 'author_name', $query_vars ) ) { global $wpdb; $author_id = $wpdb->get_var( $wpdb->prepare( "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key='nickname' AND meta_value = %s", $query_vars['author_name'] ) ); if ( $author_id ) { $query_vars['author'] = $author_id; unset( $query_vars['author_name'] ); } } return $query_vars; } //使用昵稱替換鏈接中的用戶名 add_filter( 'author_link', 'wpdaxue_author_link', 10, 3 ); function wpdaxue_author_link( $link, $author_id, $author_nicename ) { $author_nickname = get_user_meta( $author_id, 'nickname', true ); if ( $author_nickname ) { $link = str_replace( $author_nicename, $author_nickname, $link ); } return $link; } |
/**
* 將WordPress作者存檔鏈接中的用戶名改為昵稱
* https://www.wpdaxue.com/use-nickname-for-author-slug.html
*/
//使用昵稱替換用戶名,通過用戶ID進行查詢
add_filter( ‘request’, ‘wpdaxue_request’ );
function wpdaxue_request( $query_vars )
{
if ( array_key_exists( ‘author_name’, $query_vars ) ) {
global $wpdb;
$author_id = $wpdb->get_var( $wpdb->prepare( "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key=’nickname’ AND meta_value = %s", $query_vars[‘author_name’] ) );
if ( $author_id ) {
$query_vars[‘author’] = $author_id;
unset( $query_vars[‘author_name’] );
}
}
return $query_vars;
} //使用昵稱替換鏈接中的用戶名
add_filter( ‘author_link’, ‘wpdaxue_author_link’, 10, 3 );
function wpdaxue_author_link( $link, $author_id, $author_nicename )
{
$author_nickname = get_user_meta( $author_id, ‘nickname’, true );
if ( $author_nickname ) {
$link = str_replace( $author_nicename, $author_nickname, $link );
}
return $link;
}
接著我們在個人資料中修改昵稱為其他名稱,如下圖,用戶 demo 的昵稱改為瞭 changmeng,這樣一來,作者存檔的鏈接就自動由 http://域名/author/demo 變成瞭 http://域名/author/changmeng
此外,記得將“公開顯示為”設置為非用戶名,這樣就OK啦!
註意:昵稱不要包含空格,同時不建議使用中文;如果是多用戶部落格,可能會存在昵稱相同的情況,這時候隻會顯示ID較早的用戶(解決思路是修改個人資料時,如果使用瞭相同昵稱,進行提示。但是還不知具體如何實現,如果有朋友知道,希望告知)
參考資料:http://wordpress.stackexchange.com/questions/5742
相關閱讀:將WordPress作者存檔鏈接中的用戶名改為用戶ID