0

I tried combining two conditions: is_page and current_user_can but it didn't work.

Found an example at StackExchange where the user role was spelled out. But the Wordpress codex says "Do not pass a role name to current_user_can(), as this is not guaranteed to work correctly." On the same page, this link is included for reference/further reading: http://docs.appthemes.com/tutorials/wordpress-check-user-role-function/

I tried adapting that code, and added this to my functions.php

function plastics_check_user_role( $role, $user_id = null ) {

if ( is_numeric( $user_id ) )
$user = get_userdata( $user_id );
else
    $user = wp_get_current_user();

if ( empty( $user ) )
return false;

return in_array( $role, (array) $user->roles );
}

Then, here's what I put in the sidebar.php file:

<?php
    if (is_page(array('page1')) && plastics_check_user_role('Administrator')) :
        echo '<div class="widget-title">Title 1</div>' . wp_nav_menu(array('theme_location'=>'menu1' ));
    elseif (is_page(array('page2'))) :
        echo '<div class="widget-title">Page 2</div>' . wp_nav_menu(array('theme_location'=>'menu2' ));
    elseif (is_page(array('page 3'))) :
        echo '<div class="widget-title">Page 3</div>' . wp_nav_menu(array('theme_location'=>'menu3' ));
    endif;
?>

Still not working. What am I missing? Is it because it's in the sidebar?


I prefer to spell out the role - not specify user capabilities - because my 5 custom user roles have exactly the same capabilities, but I restrict pages based on the role. (Hacky workaround: I could add custom capabilities to each role, but that seems like a strange way of doing it....)

1

Changed the code in functions.php to this:

function get_user_role() {
global $current_user;

$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);

return $user_role;
}

And in the sidebar.php:

<?php
if (is_page(array('page1')) && get_user_role('Administrator')) :
    echo '<div class="widget-title">Title 1</div>' . wp_nav_menu(array('theme_location'=>'menu1' ));
elseif (is_page(array('page2'))) :
    echo '<div class="widget-title">Page 2</div>' . wp_nav_menu(array('theme_location'=>'menu2' ));
elseif (is_page(array('page 3'))) :
    echo '<div class="widget-title">Page 3</div>' . wp_nav_menu(array('theme_location'=>'menu3' ));
endif;
?>

Sources: https://stackoverflow.com/questions/1458362/how-to-get-the-currently-logged-in-users-role-in-wordpress

http://wordpress.org/support/topic/how-to-get-the-current-logged-in-users-role?replies=10#post-1600295

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.