0

I have 3 user roles: role1, role2 and admin. I have 3 divs and a different one should show depending on the logged in persons role. So role1 should see div1 only, role2 should see div2 only and admin should see both.

How do I also display both to non-logged in users? I dont how to write that ie. target people that aren't logged in.

<?php 
    global $user_login, $current_user; 
    if (is_user_logged_in()) {
    get_currentuserinfo();
    $user_info = get_userdata($current_user->ID);
    if (in_array('role1', $user_info->roles)) { 
?>    
    <div class="div1">CONTENT</div></a>
<?php
 }
  }
?>  

<?php 
    global $user_login, $current_user; 
    if (is_user_logged_in()) {
    get_currentuserinfo();
    $user_info = get_userdata($current_user->ID);
    if (in_array('role2', $user_info->roles)) { 
?> 
    <div class="div2">CONTENT</div>
<?php
 }
  }
?>  

<?php 
    global $user_login, $current_user; 
    if (is_user_logged_in()) {
    get_currentuserinfo();
    $user_info = get_userdata($current_user->ID);
    if (in_array('administrator', $user_info->roles)) { 
?> 
    <div class="div1">CONTENT</div>
    <div class="div2">CONTENT</div>
<?php
 }
  }
?>  
jfar_2020
  • 161
  • 4
  • 23

1 Answers1

0

We should try to reuse the code as much as possible and also should try to keep the code clean and short enough so that it is understandable.

Rendering of each block should be a responsibility of a function so that it can be called as necessary. Also since the user's role is already identified using $user_info = get_userdata($current_user->ID); we do not need to set the variable again. In your same code was repeated multiple times which should be avoided.

<?php 

global $user_login, $current_user; 
$user_is_logged_in = is_user_logged_in();
if ($user_is_logged_in) {
    get_currentuserinfo();
    $user_info = get_userdata($current_user->ID);
}
?>


<?php if ($user_is_logged_in && (in_array('role1', $user_info->roles) || in_array('administrator', $user_info->roles))): ?>
    <div class="div1">CONTENT for role1</div>
<?php endif ?>

<?php if ($user_is_logged_in && (in_array('role2', $user_info->roles) || in_array('administrator', $user_info->roles))): ?>
    <div class="div2">CONTENT for role2</div>
<?php endif ?>
Ahsan
  • 3,845
  • 2
  • 36
  • 36