get_user_option()
云策文档标注
概述
get_user_option() 函数用于检索用户选项,这些选项可以是针对单个站点或整个网络的。它优先检查站点特定选项,然后回退到网络范围选项,并支持通过过滤器进行自定义。
关键要点
- 函数用于获取用户选项,支持站点特定和网络范围选项的检索。
- 如果未提供用户 ID,则自动使用当前用户 ID。
- 参数包括必填的选项名称、可选的用户 ID 和一个已弃用的参数。
- 返回值是用户选项值(成功时)或 false(失败时)。
- 内部实现通过 get_userdata() 获取用户数据,并使用 wpdb::get_blog_prefix() 构建选项前缀。
- 提供动态过滤器 get_user_option_{$option} 以修改结果。
代码示例
$bar = get_user_option( 'show_admin_bar_front', get_current_user_id() );
if ( $bar == 'true' ) {
echo 'The admin bar is enabled';
} else {
echo 'The admin bar is disabled';
}
原文内容
Retrieves user option that can be either per Site or per Network.
Description
If the user ID is not given, then the current user will be used instead. If the user ID is given, then the user data will be retrieved. The filter for the result, will also pass the original option name and finally the user data object as the third parameter.
The option will first check for the per site name and then the per Network name.
Parameters
$optionstringrequired-
User option name.
$userintoptional-
User ID.
$deprecatedstringoptional-
Use get_option() to check for an option in the options table.
Source
function get_user_option( $option, $user = 0, $deprecated = '' ) {
global $wpdb;
if ( ! empty( $deprecated ) ) {
_deprecated_argument( __FUNCTION__, '3.0.0' );
}
if ( empty( $user ) ) {
$user = get_current_user_id();
}
$user = get_userdata( $user );
if ( ! $user ) {
return false;
}
$prefix = $wpdb->get_blog_prefix();
if ( $user->has_prop( $prefix . $option ) ) { // Blog-specific.
$result = $user->get( $prefix . $option );
} elseif ( $user->has_prop( $option ) ) { // User-specific and cross-blog.
$result = $user->get( $option );
} else {
$result = false;
}
/**
* Filters a specific user option value.
*
* The dynamic portion of the hook name, `$option`, refers to the user option name.
*
* @since 2.5.0
*
* @param mixed $result Value for the user's option.
* @param string $option Name of the option being retrieved.
* @param WP_User $user WP_User object of the user whose option is being retrieved.
*/
return apply_filters( "get_user_option_{$option}", $result, $option, $user );
}
Hooks
- apply_filters( “get_user_option_{$option}”, mixed $result, string $option, WP_User $user )
-
Filters a specific user option value.
Changelog
| Version | Description |
|---|---|
| 2.0.0 | Introduced. |
Skip to note 2 content
Codex
Basic Example
$bar = get_user_option( 'show_admin_bar_front', get_current_user_id() ); if ( $bar == 'true' ) { echo 'The admin bar is enabled'; } else { echo 'The admin bar is disabled'; }