show content based on logged in user=role in wordp

2019-08-21 20:31发布

问题:

I have this working ok:

<?php global $user_login; get_currentuserinfo();
if ($user_login) :?>
<li><a href="<?php echo get_site_url(); ?>/wp-admin/admin.php?page=download_report&download_report">Download Inventory of Mobile Apps</a></li>
<?php endif; ?>

But I am seeking to alter it to display this specific content based on logged in user ROLE. So basically something like if role is=administrator show, if not hide for all other logged in users.

|||| How can I alter my current code to write an if statement that checks for logged in user role then if specific role like admin, show content; and if not hide?

Fail Log: Recent:

<?php global $user_login; get_currentuserinfo();
if( is_user_logged_in() ) {
            if( !current_user_can( 'administrator' ) ) { :?>
<li><a href="<?php echo get_site_url(); ?>/wp-admin/admin.php?page=download_report&download_report">Download Inventory of Mobile Apps</a></li>
<?php endif; ?>

Most Recent:

<?php 
global $user_login, $current_user; 
get_currentuserinfo();
$user_info = get_userdata($current_user->ID);
if (in_array('administrator', $user_info->roles)) {

<li><a href="<?php echo get_site_url(); ?>/wp-admin/admin.php?page=download_report&download_report">Download Inventory of Mobile Apps</a></li>
    }
?>  

回答1:

Perhaps something like:

<?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)) {
        // content
    }
}
?>

Combined with your most recent code:

<?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)) { 
?>    
<li><a href="<?php echo get_site_url(); ?>/wp-admin/admin.php?page=download_report&download_report">Download Inventory of Mobile Apps</a></li>
<?php
    }
}
?>  


标签: php wordpress