Wp php get current user

_wp_get_current_user() │ WP 4.5.0

Retrieves the current user object. Will set the current user, if the current user is not set. The current user will be set to the logged-in person. If no user is logged-in, then it will set the current user to 0, which is invalid and won’t have any permissions. This function is used by the pluggable functions wp_get_current_user() and get_currentuserinfo(), the latter of which is deprecated but used for backward compatibility.

This is an internal function for using it by WP core itself. It’s not recommended to use this function in your code.

Hooks from the function

Return

Usage

Notes

Changelog

_wp_get_current_user() wp get current user code WP 6.2.2

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; >/** * Filters 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|false $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; >wp_set_current_user( $user_id ); return $current_user; >

Источник

wp_get_current_user() │ WP 2.0.3

Retrieve the current authorized user data (WP_User object). Sets current user, if not set yet. Sets the current user, the first time the function is called, then the result is stored in the global variable $current_user . If the user is not authorized, an empty user will be sets: wp_set_current_user( 0 ).

This function can be used starting from plugins_loaded action. If you call it earlier, you will get fatal error.

Returns 0 if used in an unauthorized REST request. One way to authorize a REST request is to specify nonce code. Read more about REST authorization.

If you really need to call this function before the plugins_loaded action, you should first enable the dependencies. However, you should do this with a full understanding of how authorization works.

// Dependencies wp_cookie_constants(); require ABSPATH . WPINC . '/pluggable.php'; $cuser = wp_get_current_user(); //> WP_User object
$current_user_id = get_current_user_id(); $current_user = wp_get_current_user();

This is a pluggable function, and it can be replaced by a plugin. It means that this function is defined (works) only after all plugins are loaded (included), but before this moment this function has not defined. Therefore, you cannot call this and all functions depended on this function directly from a plugin code. They need to be called on plugins_loaded hook or later, for example on init hook.

Читайте также:  Отправляем JSON-данные на сервер

Function replacement (override) — in a plugin you can create a function with the same name, then it replace this function.

Return

WP_User . Current WP_User instance.

WP_User Object ( [data] => stdClass Object ( [ID] => 1 [user_login] => alex [user_pass] => $P$B/NlqweHhtrD6HthgjF5UYOMdT77.x0 [user_nicename] => alex-1 [user_email] => [email protected] [user_url] => [user_registered] => 2010-03-26 09:27:40 [user_activation_key] => 1987530484:$P$ByO33dFHn3aWu.Pe4Uw.MUhGGT59zc1 [user_status] => 1646545990 [display_name] => Alex ) [ID] => 1 [caps] => Array ( [administrator] => 1 ) [cap_key] => wp_capabilities [roles] => Array ( [0] => administrator ) [allcaps] => Array ( [switch_themes] => 1 [edit_themes] => 1 [activate_plugins] => 1 [edit_plugins] => 1 [edit_users] => 1 [edit_files] => 1 [manage_options] => 1 [moderate_comments] => 1 [manage_categories] => 1 [manage_links] => 1 [upload_files] => 1 [import] => 1 [unfiltered_html] => 1 [edit_posts] => 1 [edit_others_posts] => 1 [edit_published_posts] => 1 [publish_posts] => 1 [edit_pages] => 1 [read] => 1 [level_10] => 1 [level_9] => 1 [level_8] => 1 [level_7] => 1 [level_6] => 1 [level_5] => 1 [level_4] => 1 [level_3] => 1 [level_2] => 1 [level_1] => 1 [level_0] => 1 [edit_others_pages] => 1 [edit_published_pages] => 1 [publish_pages] => 1 [delete_pages] => 1 [delete_others_pages] => 1 [delete_published_pages] => 1 [delete_posts] => 1 [delete_others_posts] => 1 [delete_published_posts] => 1 [delete_private_posts] => 1 [edit_private_posts] => 1 [read_private_posts] => 1 [delete_private_pages] => 1 [edit_private_pages] => 1 [read_private_pages] => 1 [delete_users] => 1 [create_users] => 1 [unfiltered_upload] => 1 [edit_dashboard] => 1 [update_plugins] => 1 [delete_plugins] => 1 [install_plugins] => 1 [update_themes] => 1 [install_themes] => 1 [manage_downloads] => 1 [manage_database] => 1 [democracy_admin] => 1 [update_core] => 1 [list_users] => 1 [remove_users] => 1 [promote_users] => 1 [edit_theme_options] => 1 [delete_themes] => 1 [export] => 1 [edit_artic] => 1 [read_artic] => 1 [delete_artic] => 1 [edit_artics] => 1 [edit_others_artics] => 1 [publish_artics] => 1 [read_private_artics] => 1 [delete_artics] => 1 [delete_private_artics] => 1 [delete_published_artics] => 1 [delete_others_artics] => 1 [edit_private_artics] => 1 [edit_published_artics] => 1 [manage_woocommerce] => 1 [view_woocommerce_reports] => 1 [edit_product] => 1 [read_product] => 1 [delete_product] => 1 [edit_products] => 1 [edit_others_products] => 1 [publish_products] => 1 [read_private_products] => 1 [delete_products] => 1 [delete_private_products] => 1 [delete_published_products] => 1 [delete_others_products] => 1 [edit_private_products] => 1 [edit_published_products] => 1 [manage_product_terms] => 1 [edit_product_terms] => 1 [delete_product_terms] => 1 [assign_product_terms] => 1 [edit_shop_order] => 1 [read_shop_order] => 1 [delete_shop_order] => 1 [edit_shop_orders] => 1 [edit_others_shop_orders] => 1 [publish_shop_orders] => 1 [read_private_shop_orders] => 1 [delete_shop_orders] => 1 [delete_private_shop_orders] => 1 [delete_published_shop_orders] => 1 [delete_others_shop_orders] => 1 [edit_private_shop_orders] => 1 [edit_published_shop_orders] => 1 [manage_shop_order_terms] => 1 [edit_shop_order_terms] => 1 [delete_shop_order_terms] => 1 [assign_shop_order_terms] => 1 [edit_shop_coupon] => 1 [read_shop_coupon] => 1 [delete_shop_coupon] => 1 [edit_shop_coupons] => 1 [edit_others_shop_coupons] => 1 [publish_shop_coupons] => 1 [read_private_shop_coupons] => 1 [delete_shop_coupons] => 1 [delete_private_shop_coupons] => 1 [delete_published_shop_coupons] => 1 [delete_others_shop_coupons] => 1 [edit_private_shop_coupons] => 1 [edit_published_shop_coupons] => 1 [manage_shop_coupon_terms] => 1 [edit_shop_coupon_terms] => 1 [delete_shop_coupon_terms] => 1 [assign_shop_coupon_terms] => 1 [edit_shop_webhook] => 1 [read_shop_webhook] => 1 [delete_shop_webhook] => 1 [edit_shop_webhooks] => 1 [edit_others_shop_webhooks] => 1 [publish_shop_webhooks] => 1 [read_private_shop_webhooks] => 1 [delete_shop_webhooks] => 1 [delete_private_shop_webhooks] => 1 [delete_published_shop_webhooks] => 1 [delete_others_shop_webhooks] => 1 [edit_private_shop_webhooks] => 1 [edit_published_shop_webhooks] => 1 [manage_shop_webhook_terms] => 1 [edit_shop_webhook_terms] => 1 [delete_shop_webhook_terms] => 1 [assign_shop_webhook_terms] => 1 [ure_edit_roles] => 1 [ure_create_roles] => 1 [ure_delete_roles] => 1 [ure_create_capabilities] => 1 [ure_delete_capabilities] => 1 [ure_manage_options] => 1 [ure_reset_roles] => 1 [edit_blocks] => 1 [edit_others_blocks] => 1 [publish_blocks] => 1 [read_private_blocks] => 1 [read_blocks] => 1 [delete_blocks] => 1 [delete_private_blocks] => 1 [delete_published_blocks] => 1 [delete_others_blocks] => 1 [edit_private_blocks] => 1 [edit_published_blocks] => 1 [create_blocks] => 1 [administrator] => 1 ) [filter] => [site_id:WP_User:private] => 1 )

If the user is not authorized, an empty object will be returned! Therefore. you SHOULD NOT use this function to determine if the user is authorized!

Читайте также:  Определитель матрицы рекурсивно python

if( wp_get_current_user() ) < echo 'It will always be printed!'; >// You need to do so: if( wp_get_current_user()->exists() ) < echo 'Authorized!'; >// Or so: if( is_user_logged_in() )

Usage

Источник

_wp_get_current_user() │ WP 4.5.0

Retrieves the current user object. Will set the current user, if the current user is not set. The current user will be set to the logged-in person. If no user is logged-in, then it will set the current user to 0, which is invalid and won’t have any permissions. This function is used by the pluggable functions wp_get_current_user() and get_currentuserinfo(), the latter of which is deprecated but used for backward compatibility.

Эта функция считается внутренней для использования самим ядром. Не рекомендуется использовать эту функцию в своем коде.

Хуки из функции

Возвращает

Использование

Заметки

Список изменений

Код _wp_get_current_user() wp get current user WP 6.2.2

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; >/** * Filters 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|false $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; >wp_set_current_user( $user_id ); return $current_user; >

Источник

Читайте также:  Изучение android studio java

wp_get_current_user()

Функция wp_get_current_user() позволяет получить информацию о текущем пользователе в виде объекта WP_User .

Возвращает объект WP_User , если пользователь авторизован (вошёл в систему). Если пользователь не авторизован, то функция автоматически установит ID пользователя равное 0 и вернёт пустой объект. Проверить, авторизован пользователь или нет, можно при помощи функции is_user_logged_in().

Пример возвращаемого объекта WP_User для администратора:

WP_User Object ( [data] => stdClass Object ( [ID] => 1 [user_login] => admin [user_pass] => $P$BMoN3hwygEeQhe6xS234ReDeMbDd3lA0 [user_nicename] => admin [user_email] => no-reply@misha.blog [user_url] => http://misha.blog [user_registered] => 2020-06-20 16:18:22 [user_activation_key] => [user_status] => 0 [display_name] => admin ) [ID] => 1 [caps] => Array ( [administrator] => 1 ) [cap_key] => wp_capabilities [roles] => Array ( [0] => administrator ) [allcaps] => Array ( [switch_themes] => 1 [edit_themes] => 1 [activate_plugins] => 1 [edit_plugins] => 1 [edit_users] => 1 [edit_files] => 1 [manage_options] => 1 [moderate_comments] => 1 [manage_categories] => 1 [manage_links] => 1 [upload_files] => 1 [import] => 1 [unfiltered_html] => 1 [edit_posts] => 1 [edit_others_posts] => 1 [edit_published_posts] => 1 [publish_posts] => 1 [edit_pages] => 1 [read] => 1 [level_10] => 1 [level_9] => 1 [level_8] => 1 [level_7] => 1 [level_6] => 1 [level_5] => 1 [level_4] => 1 [level_3] => 1 [level_2] => 1 [level_1] => 1 [level_0] => 1 [edit_others_pages] => 1 [edit_published_pages] => 1 [publish_pages] => 1 [delete_pages] => 1 [delete_others_pages] => 1 [delete_published_pages] => 1 [delete_posts] => 1 [delete_others_posts] => 1 [delete_published_posts] => 1 [delete_private_posts] => 1 [edit_private_posts] => 1 [read_private_posts] => 1 [delete_private_pages] => 1 [edit_private_pages] => 1 [read_private_pages] => 1 [delete_users] => 1 [create_users] => 1 [unfiltered_upload] => 1 [edit_dashboard] => 1 [update_plugins] => 1 [delete_plugins] => 1 [install_plugins] => 1 [update_themes] => 1 [install_themes] => 1 [update_core] => 1 [list_users] => 1 [remove_users] => 1 [promote_users] => 1 [edit_theme_options] => 1 [delete_themes] => 1 [export] => 1 [administrator] => 1 ) [filter] => [site_id:WP_User:private] => 1 )

Пример 1

Первый пример будет из урока Комментарии видеокурса Создание темы WordPress.

$current_user = wp_get_current_user(); // получили объект с данными текущего авторизованного пользователя echo '

Вы вошли как' . $current_user->display_name . '.

'
; // получим

Вы вошли как admin.

Пример 2

Мы можем получить все права (capabilities) текущего пользователя. По умолчанию все права различаются в зависимости от роли пользователя. Можно конечно проверить определенное право с помощью функции current_user_can(), но лучше распечатать все текущие права пользователя для наглядности.

echo '
'; // используем тег pre, чтобы получить читаемый код print_r( wp_get_current_user()->allcaps );

Текущий пользователь имеет роль подписчик и мы получим следующий массив данных с его правами.

Array ( [read] => 1 [level_0] => 1 [subscriber] => 1 )

Если хотите посмотреть все права администратора, то они приведены выше, в примере возвращаемого объекта.

Роман

WordPress разработчик.
Улыбаюсь я потому, что WordPress - лучшая cms!

Источник

Оцените статью