2

In WordPress/WooCommerce, I have a web shop that uses User Roles and based on those roles, you can see different Pages/Products.

What I'm looking to do is add a way that allow some User role to temporary see, the same stuff than other User Role.

Lets say, I have 4 different User roles:

  1. Admin
  2. Premium Member
  3. Standard Member
  4. Default Member

Is it possible for me to make (lets say a button) that when pressed, will display restricted content to a "Default Member" to view it as if it was a "Premium Member"?

Preferably I would like NOT to permanently change the user's role, and then change it back. Is this possible in some way?

Thanks

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Mac
  • 334
  • 1
  • 3
  • 13

1 Answers1

3

Yes it's possible, if you add an OR condition in your page template for yours existing user roles view (or display) conditions. This condition will be based on a custom field set in the user meta data.

So when you will click on that "button", it will update the value of the user custom field and will allow to display the "premium content" (for example). For this purpose you can use get_user_meta() and update_user_meta() Wordpress Functions.

You define first that 2 variables at the beginning of your php file or template:

// Getting the user iD
$user_id = get_current_user_id();
// Looking if our user custom field exist and has a value
$custom_value = get_user_meta($user_id, '_custom_user_meta', true);

Then your condition is going to be a little like:

if($user_role == 'premium' && $custom_value){
    // Displays the premium content
}

Now when pressing on your "button", it will update that $custom_value to true, allowing this user to see that premium content on form submission (or with ajax).

So you will have to put this code just after the 2 variables above:

if('yes' == $_post['button_id']){
    // $custom_value and $user_id are already defined normally (see above)
    if($custom_value){
        update_user_meta($user_id, '_custom_user_meta', 0); // updated to false
    } else {
        update_user_meta($user_id, '_custom_user_meta', 1); // updated to true
    }
}

This should work…


Update (based on your comment)

Alternatively, for The Admin as in your comment, You can target 'administrator' user role in your condition AND (&&) a special cookie that will be set by your "button". This way you will not have to use a custom field.

Community
  • 1
  • 1
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • My initial thought/try was something along the lines of what you described above, but i see multiple problems with it. (1): Lets say its only the admin i want to be able to see how it look for other roles, i dont want to change his role permanently:(. (2): I Have to push a button multiple times to switch back and forth. (3): Im forced to use a custom variable - not that their is anything wrong with that, but obviously i would prefer not to :) – Mac Jan 24 '17 at 11:50