最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

(solved) getting post author's user role

programmeradmin0浏览0评论

we can use

$user = wp_get_current_user();
    if ( !in_array( 'administrator', (array) $user->roles ) )

to get the user role of the viewer. but i want to ignore who views. i want to get who writes the post. need something like

$user = wp_get_post_author();
    if ( !in_array( 'administrator', (array) $user->roles ) )

so that i can show results depending on the user who writes the post while ignoring who views that.

we can use

$user = wp_get_current_user();
    if ( !in_array( 'administrator', (array) $user->roles ) )

to get the user role of the viewer. but i want to ignore who views. i want to get who writes the post. need something like

$user = wp_get_post_author();
    if ( !in_array( 'administrator', (array) $user->roles ) )

so that i can show results depending on the user who writes the post while ignoring who views that.

Share Improve this question edited Dec 22, 2020 at 3:37 Abdullah Al Muaz asked Dec 15, 2020 at 9:13 Abdullah Al MuazAbdullah Al Muaz 133 bronze badges 3
  • Where are you doing that - in the frontend or backend? And what is the problem with your example (besides not using get_the_author())? – kero Commented Dec 15, 2020 at 9:29
  • @kero We need the WP_User object and get_the_author just returns the display name. – Rup Commented Dec 15, 2020 at 10:25
  • What are you trying to do? If you are counting post views, but want to ignore the author, then this is the completely wrong approach. – Jacob Peattie Commented Dec 18, 2020 at 13:31
Add a comment  | 

3 Answers 3

Reset to default 1

You can find the author's ID on the post and fetch their user object from that with get_userdata(), e.g.

$author = get_userdata( get_post()->post_author ) ;
if ( !in_array( 'administrator', (array) $author->roles ) ) { ... }

I tried so hard and got so far But in the end it doesn't even matter

$post_id = get_queried_object_id();
$author_ID = get_post_field( 'post_author', $post_id );
$authorData = get_userdata( $author_ID );
if ( !in_array( 'administrator', $authorData->roles)){... ...}

Retrieve the current user object from the wp_get_current_user() and then check administrator role in in_array.

$user = wp_get_current_user();
if ( in_array( 'administrator', (array) $user->roles ) ) {
    //The user has the "administrator" role
}

Here I have shared the link for wp_get_current_user() and in_array() for better understanding.

发布评论

评论列表(0)

  1. 暂无评论