How to display content only if the WordPress user has a certain role

Introduction

I was working on a WordPress website and needed to show a button only if the user which visited the page had a certain role.

display content user role based

The page I was working on used a certain php template.

I order to achieve the desired result I had to add some PHP programming.

PHP code to show content based on user role

You can add the below content to your WP template php file, right in the place where you want to display the content for users with a certain role.

if ( is_user_logged_in() ) {

$userinfo = wp_get_current_user();
$user_id = $userinfo->ID;

// get the user object.
$user = get_userdata( $user_id );

// get all the user roles as an array
$user_roles = $user->roles;

// check if role is present in the array - the code uses the role "student"
if ( in_array( 'student', $user_roles, true ) ) { 
	
echo "Add content here";

  } 
}

You only need to change the user role name to the one you want. And, of course, you need to add your own content where I used the echo ( a button, a link, a video, some text or an image).

Conclusion

Please let me know if this solution to display content based on WordPress user role is helpful for you and contact me if you need more info.

Comments closed

Please contact me, if you have any questions or suggestions.