Simplifying how I currently show featured posts, when a post is submitted by a full member, a post_meta value is added to the post which is then styled differently.

But Id like to do it based on the post authors, user role instead.

So if a the user who submitted the post is a “full_member”, their post is automatically featured without the need for post_meta to be queried.

I’ve tried something like this which is in the archive template loop, and just adds a “featured-listing” class to a wrapping div, but I don’t think I’m looking at it in the correct way.

 <?php $user = wp_get_current_user();
if ( in_array( 'full_member', (array) $user->roles ) ) { ?>

featured-listing

<?php } ?>

EDIT

Part 1 has been resolved using Nathan’s original answer for the class issue , his answer has expanded since then which doesnt work for me, so ive pasted the solution that did work below :

//* If the post author is a full member, they get a featured listing
function which_class() {
  return post_author_role_in( 'full_member' ) ? 'featured-listing' : 'regular-listing';
}

//* Determine if the post author is in the $role
function post_author_role_in( $role ) {
  return in_the_loop() ? user_role_in( get_the_author_meta( 'ID' ), $role ) : false;
}

//* Determine if the $user_id is in the $role
function user_role_in( $user_id, $role ) {
  return in_array( $role, ( new WP_User( $user_id ) )->roles );
}

Part 2 However I still need a solution for

Id still like to use a conditional to completely hide certain elements within the template, is there an IF condition which says something like IF post author is in X role, display this, else display this. ?

Please advise 🙂

2 Answers
2

One way to do it is getting the author data and checking it’s role with get_userdata() Codex

For that you will need the user ID, and you can get that with get_post_field() Codex

You will need the post ID to use the get_post_field(), so you can use the get_queried_object_id()Codex

So, you would have something like:

//gets the ID of the post
$post_id = get_queried_object_id();

//gets the ID of the author using the ID of the post
$author_ID = get_post_field( 'post_author', $post_id );

//Gets all the data of the author, using the ID
$authorData = get_userdata( $author_ID );

//checks if the author has the role of 'subscriber'
if (in_array( 'subscriber', $authorData->roles)):
    //show the content for subscriber role
else:
    //show the content for every other role
endif;

Is there a faster/simpler way to do it? Yes

So why I gave you this ‘around the world’ solution’? Because from my experience, this way you can prevent a lot of stuff that might mess up with your result later on

So, what about another way of doing it? Since there are a few ways to do it, you can for example use the global $authordata. You can check the globals WordPress has here

Leave a Reply

Your email address will not be published. Required fields are marked *