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.

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 Dec 15 '20 at 9:29
  • @kero We need the WP_User object and get_the_author just returns the display name. – Rup Dec 15 '20 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 Dec 18 '20 at 13:31
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 ) ) { ... }
1

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)){... ...}
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.