0

I am trying to hide cart menu icon if the logged in user is not a subscriber. Right now I have the following code in my functions.php, but I still can see the cart if I am a subscriber.

  add_filter( 'wpmenucart_menu_item_wrapper', 'wpmenucart_hide_for_visitors', 10, 1 );
function wpmenucart_hide_for_visitors( $menu_item_li ) {
    if ( is_user_logged_in() || !current_user_can( $current_user, "subscriber" )) {
        return $menu_item_li;
    } else {
        return;
    }
}

I can't see what's wrong with my code.

1

You have errors in the code

First, you are using current_user_can() function the wrong way. It has two parameters — $capability and $object_id. You don't need the latter one, so, in your case:

current_user_can('subscriber')

In my opinion, it's better to use capability instead of user role in this function. For example, subscribers can't edit posts, unlike other user roles, so I'd change 'subscriber' to 'edit_posts':

Second, the if condition. Your code says that user must be logged in OR his role must not be a subscriber. It should sound like the user must be logged in AND must be not a subscriber.

add_filter( 'wpmenucart_menu_item_wrapper', 'wpmenucart_hide_for_visitors', 10, 1 );

function wpmenucart_hide_for_visitors( $menu_item_li )
{
    // user is logged in AND his role is higher than a subscriber
    if ( is_user_logged_in() && current_user_can('edit_posts') ) {
        return $menu_item_li;
    } else {
        return;
    }
}

See current_user_can in the Codex.

  • Hi, thanx for your reply. I tried your suggestion, but still no go. It's weird, because I do manage to hide it for non-logged users with my code. It's just that user roles (or capabilities) are problem. Any other suggestions maybe? – Nancy Oct 17 '16 at 9:32
  • Do you use a caching plugin? If so, purge the plugin cache and browser cache too. – Max Yudin Oct 17 '16 at 9:36
  • I don't use any cache plugin. The fact is - when I remove the code related to user, it is hidden. The second I add the user related code, it is shown. Weird. – Nancy Oct 17 '16 at 9:45
  • Oh, my fault. I've left a piece of your code unedited. You need AND (&&) instead of OR (||) and no need in ! negation. I've edited the answer. – Max Yudin Oct 17 '16 at 9:53
  • Oh, that's right! I can't believe I didn't notice what was wrong with it. Thank you very much for your help! – Nancy Oct 17 '16 at 9:57

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.