問題描述
截至大約 10 天前,WordPress 4.5 developers deprecated get_currentuserinfo()作為可插拔功能。不幸的是,我的插件使用自己的 get_currentuserinfo() 從外部數據庫登錄用户。
這將需要重寫該插件的 WP 4.5 兼容性區域。
既然我不是唯一一個使用這個功能的橋樑,那麼開發者應該採取什麼方向呢?
最佳解決方案
答案在於 wp_get_current_user()可插拔功能。我只是將函數名 get_currentuserinfo()改為 wp_get_current_uesr(),然後確保返回值不是布爾值,但返回 $ current_user 。
這似乎運作良好,包括緩存等。
希望這有助於別人。
if ( ! function_exists( 'wp_get_current_user' ) ) :
/**
* This replacement function will no longer work after WordPress 4.5
* The pluggable function was deprecated in WP 4.5
*
* @return void|boolean
*
* @since 2.5.1.03
* Added apply_filter to match WP get_currentuserinfo()
*
* @since 3.0.2.01
* wp_get_current_user instead of get_currentuserinfo()
*/
function wp_get_current_user() {
global $current_user;
if ( ! empty( $current_user ) ) {
if ( $current_user instanceof WP_User ) {
return $current_user;
}
// Upgrade stdClass to WP_User
if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
$cur_id = $current_user->ID;
$current_user = null;
wp_set_current_user( $cur_id );
return $current_user;
}
// $current_user has a junk value. Force to WP_User with ID 0.
$current_user = null;
wp_set_current_user( 0 );
return $current_user;
}
if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
wp_set_current_user( 0 );
return $current_user;
}
$visitor = XenWord::getVisitor();
$user_id = $visitor['user_id'];
// Conditional for no XenForo user is logged in
if ( $user_id == 0 ) {
$current_user = null;
wp_set_current_user( 0 );
return $current_user;
}
/**
* Filter the current user.
*
* The default filters use this to determine the current user from the
* request's cookies, if available.
*
* Returning a value of false will effectively short-circuit setting
* the current user.
*
* @since 3.9.0
*
* @param int|bool $user_id User ID if one has been determined, false otherwise.
*/
$user_id = apply_filters( 'determine_current_user', false );
if ( ! $user_id ) {
wp_set_current_user( 0 );
return $current_user;
}
$current_user = get_userdata( $user_id );
wp_set_current_user( $user_id );
wp_validate_auth_cookie($cookie = '', $scheme = '');
// Check to determine if adding XF users to WP database
XenWord_XF_Users::check_options();
return $current_user;
}
endif;
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。