I am looking to display content based on multiple different user roles.
The aim is to display content for two or three different user roles, and then block it for other user roles, displaying a message that it is only for certain logged in users.
So far, I have the following:
<?php
global $user_login, $current_user;
get_currentuserinfo();
$user_info = get_userdata($current_user->ID);
$roles = array (
'administrator',
'subscriber',
);
if (is_user_logged_in() && in_array( $roles, $user_info->roles)) {
//content here
} else {
// they aren't logged in, so show them the login form
}
?>
At the moment, the issue I am having seems to be that the code is looking for both the administrator and subscriber roles at the same time and as a result, the if statement is not satisfied and the login form shows.
If I change $roles to 'administrator' or 'subscriber', it then works fine.
So, how would I search through the array to display either role, not all of them.
Thanks
You could use:
array_intersect (link)
array_intersect will check between two array to see if the needle ($roles) exists in the haystack ($user_info->roles). I have tested this against my own and works well.
See below the use of array_intersect.
<?php
global $user_login, $current_user;
get_currentuserinfo();
$user_info = get_userdata($current_user->ID);
$roles = array (
'administrator',
'subscriber',
);
if (is_user_logged_in() && array_intersect( $roles, $user_info->roles)) {
echo 'success';
} else {
echo 'failure';
}
?>
Example 1: LINK the $roles array does not match.
Example 2: LINK the $roles array has one match.
Related
what is wrong with this code?
I really just want to display the current users role, but it seems impossible :-(
I have tried this:
<?php if ( is_user_logged_in() ) {
global $current_user; get_currentuserinfo();
} else { }
global $current_user;
get_currentuserinfo();
echo 'User role: ' . $current_user->role . "";
?>
And this:
<?php
$current_user = wp_get_current_user();
printf( __( 'Netværksgruppe: %s', 'textdomain' ), esc_html(
$current_user->role ) ) ;
?>
and about 100 more, but nothing seems to work...
(I have tried with plugins, php snippets, functions.php, anything)
Any help would be much appreciated :-)
The user role isn't a string value you can output like that. Take a look at the WP_User object.
$user->roles is actually an array. Most WP installations result in each user having a single role. but there are many reasons why a user may have multiple roles. So you'll either need to output all of the roles using something like implode() or just output the first role by index.
// Current WP_User object
$user = wp_get_current_user();
// All Roles (implode the array)
printf( 'All my roles are: %s.', implode( ', ', $user->roles ) );
# Result: "All my roles are: administrator, custom_role, some_role."
// Or single role (only output the first result)
printf( 'My role is: %s.', $user->roles[0] );
# Result: "My role is: administrator."
See documentation of get_currentuserinfo() -
https://codex.wordpress.org/Function_Reference/get_currentuserinfo
$current_user - is object, not string. If you need email of curent user:
global $current_user;
get_currentuserinfo();
echo 'User email: ' . $current_user->user_email . "\n";
I am only using Wordpress with Woocommerce. Is there a way to get user group name based on logged in user's info?
I have group of users called 'Group1' and assigned 2 users to it - user1, user12
I have the second group of users called 'Group2' and assigned 2 users to it - user2 and user23.
Now I need to check from which user group is the logged in user (all users have the same role - Customers).
Here is the sample of the code of what I am trying to do:
$user_logged = wp_get_current_user();
$user_group_name = // how to get user_logged's group name ?
if ($user_group_name == 'Group1') // do 1st
if ($user_group_name == 'Group2') // do 2nd
Names of the groups will be not changed so I will put them as strings into the code. However I need to get dynamically after user loggs in the name of the group he is assigned to.
How can I do it ?
Any help is appreciated.
You almost made it. Based on documentation, wp_get_current_user() return WP_User object that has properties roles (the roles the user is part of).
$roles = wp_get_current_user()->roles;
if (in_array("Group1", $roles)) {
// do 1st
}
if (in_array("Group2", $roles)) {
// do 2nd
}
Hope it helps
If you mean that you want to know what the role of an online user is?
Finally, you should use the following code.
$get = wp_get_current_user();
if ( in_array( 'administrator', $get->roles ) )
// do 1st
if ( in_array( 'editor', $get->roles ) )
// do 2st
if ( in_array( 'group1', $get->roles ) )
// do 3st
if ( in_array( 'groupN', $get->roles ) )
// do N st
You can use easily and directly current_user_can() WordPress dedicated function with a specific user role (or a user capability) like:
if ( current_user_can( 'Group1' ) ) {
// do 1st
} elseif ( current_user_can( 'Group2' ) ) {
// do 2st
}
WordPress and Woocommerce don't provide any Usergroup functionality by default. What related plugin are you using for those Usergroups.
You need to search in the database table wp_usermeta to see if 'Group1' or 'Group2' are assigned to users and give us the meta_key used for it.
Use wp_get_current_user()->roles to retrieve the groups the user is a member of.
$roles = wp_get_current_user()->roles;
if (in_array('group1',$roles)) {
echo 'Do something here for group 1';
}
Currently, LearnDash has a function (to be added to functions.php) that allows you to auto enroll a specific user in a course. I was wondering if a simple function could be added to my theme's function file and change this from user_id to a user ROLE? That way every user in that role is enrolled.
Here is the starting point: (found in the dev section on Learndash)
//* To enroll user to course:
ld_update_course_access($user_id, $course_id, $remove = false);
I have tried this:
//* Add users to course by role
ld_update_course_access($role_name = Subscriber, $course_id = 949, $remove = false);
On the "edit course" page editor I now see "1,0,12,Subscriber" inside the "course access list" but it doesn't actually work. Obviously, that access list is working with users only.
My thought process is creating a function that will:
1) Get user IDs from user role "My-Custom-Role"
2) Return IDs and update course access.
Is something like this possible?
Yep, totally possible. The get_users() function allows you to get a list of users by role. See: https://codex.wordpress.org/Function_Reference/get_users
For example:
$users = get_users( [ 'role__in' => [ 'subscriber', 'author' ] ] );
foreach ( $users as $user ) {
ld_update_course_access( $user->ID, 949, false );
}
I worked with the development team and came up with a different although incomplete solution, so I've marked Linnea's as correct, because it works as asked in the question. This solution goes through their access hook sfwd_lms_has_access, however the "course list" never gets updated so a user is not officially "enrolled" until they start the course. By this I mean, you wont see them enrolled in the course on their profile, but if they start a lesson, it all of a sudden shows up! Thought it might help to post here in case it may help anyone as a starting point.
add_filter( 'sfwd_lms_has_access', function( $return, $post_id, $user_id ) {
if ( empty( $user_id ) ) {
$user_id = get_current_user_id();
}
if(empty($user_id))
return $return;
$course_id = learndash_get_course_id( $post_id );
$allowed_course_ids = array( 949, 1135 );
if( !in_array($course_id, $allowed_course_ids))
return $return;
if(user_can($user_id, "3a_textbook"))
return true;
if(user_can($user_id, "subscriber"))
return true;
return $return;
}, 10, 3 );
I have a Wordpress Memberships website that is built on WooCommerce with WooCommerce Memberships plugin to restrict certain pages to members only.
Some of those pages are "drip-fed"... ie. Access to those pages opens 3 days after purchase, etc. I have set this up in WooMemberships.
I am trying to simply do a PHP conditional check to see if the current user has access to a certain page.
I have found this code piece in the docs: wc_memberships_is_post_content_restricted()
However, I have been unable to make it work.
Is there a code snippet which will basically do a PHP IF statement on whether the current user has access to a certain page (using page ID)?
eg:
if ( current_user_has_access(page_ID) ) { DO SOMETHING } else { DON'T }
Thanks.
I'm not sure if this helps but here is my take on it. I first go through all of the users active membership and then I check the content $rules to see if the restricted plans are a part of the users membership plans (in_array)
function can_user_access_content($user_id,$post_id){
//check if there's a force public on this content
if(get_post_meta($post_id,'_wc_memberships_force_public',true)=='yes') return true;
$args = array( 'status' => array( 'active' ));
$plans = wc_memberships_get_user_memberships( $user_id, $args );
$user_plans = array();
foreach($plans as $plan){
array_push($user_plans,$plan->plan_id);
}
$rules = wc_memberships()->get_rules_instance()->get_post_content_restriction_rules( $post_id );
foreach($rules as $rule){
if(in_array($rule->get_membership_plan_id(), $user_plans)){
return true;
}
}
return false;
}
Usage would be something like:
if(can_user_access_content(get_current_user_id(),$post->ID)){
//do whatever here
}
I'm dealing with the same issue at StoryMoment.com (we produce audio + eBook story series for kids).
This is how I've dealt with it. I use the following in a page template to show or hide page elements based on access. The wc_memberships_view_delayed_post_content would change based on the type of content.
You can see the other options in the file:
class-wc-memberships-capabilities.php
<?php
$has_access = current_user_can( 'wc_memberships_view_delayed_post_content', $post->ID );
if ($has_access) {
//do something
} else {
//do something else
}
?>
You will have to Replace (in the conditions):
$page_id by your page ID number (for example: is_page(42))
$membership_plan by the slug of the plan ('plan_slug') or related post ID.
The conditions:
wc_memberships_is_post_content_restricted($page_id) => true if $page_id is retracted.
is_page($page_id) => true if is actual $page_id.
wc_memberships_is_user_active_member( $membership_plan ) => true actual user is an active member for this $membership_plan plan. In that case the access to the page is granted by the suscription plan of the user.
You can remove some of the conditions, if not needed, and fine tune for your needs.
if( wc_memberships_is_post_content_restricted() && is_page($page_id) && wc_memberships_is_user_active_member( $membership_plan ) ) {
// do something
} else {
// don't
}
--- Update ---
The only function related to restriction and (or) time access are:
1) wc_memberships_restrict( $content, $membership_plans, $delay, $exclude_trial ) just like shortcode [wcm_restrict] (so not useful)…
2) wc_memberships_get_user_access_time( $user_id, $target, $action, $gmt ): Parameters
$user_id // for a logged 'user ID'
$target : array('post' => id, 'product' => id) // content_type and content_id
$action : 'view' or 'purchase' // Type of access (products only)<br>
$gmt => : true or false // (selection of the time zone)
// Returns user access start timestamp (in site timezone) for content or a product
Reference: WooCommerce Memberships Function Reference
I am creating user specific content using ACF User field to determine which user can see what. My code below is working perfectly to show the correct content to the user selected and something different to everyone else -
<?php
$client = get_field('client');
$userID = $client['ID'];
$user_id = get_current_user_id();
if ($user_id == $userID ) {
echo 'YOUR OWN PAGE';
} else {
echo 'NOT YOUR PAGE';
}
?>
However I need to simply add an 'or' statement so any user that is an admin can see all content regardless of who they are, something like below (which doesn't work) -
if ($user_id == $userID ) || is_admin() {
All help is greatly appreciated.
Your brackets are wrong that is all.
if ($user_id == $userID || is_admin() ) {
This assumes the is_admin() function works though :)
While Christian's answer fixes the typo in the question, it doesn't provide a working solution.
The documentation for is_admin() states the following:
This Conditional Tag checks if the Dashboard or the administration panel is attempting to be displayed. It should not be used as a means to verify whether the current user has permission to view the Dashboard or the administration panel (try current_user_can() instead). This is a boolean function that will return true if the URL being accessed is in the admin section, or false for a front-end page.
And further down in the notes section:
is_admin() is not intended to be used for security checks. It will
return true whenever the current URL is for a page on the admin side
of WordPress. It does not check if the user is logged in, nor if the
user even has access to the page being requested. It is a convenience
function for plugins and themes to use for various purposes, but it is
not suitable for validating secured requests.
I do understand the logic that could lead one to think that is_admin() checks if the current user is an administrator. However, checking with the WordPress documentation(and I have to say it's really good for commonly used functions) is always a good idea.
Now that we've got that out of the way, there are two simple options that you can use in order to figure out if the current user has administrator privileges:
1. If you're not going to use WordPress Multisite, or if you will want to only allow Super Administrators to see the content
is_super_admin():
Determine if user is a network (super) admin. Will also check if user is admin if network mode is disabled.
You can pass the ID of a given user to the function, or in your case just do this:
if ( $user_id == $userID || is_super_admin() ) {
2. If you're going to use WordPress Multisite and you will want to allow Super Administrators and site Administrators to see the content
We can create our own function that works very similar to is_super_admin(), except for in a Multisite environment it also checks if the current user is an administrator(in the is_super_admin() function, this is defined by the user having the delete_users capability). Here's the code:
function my_is_user_admin( $user_id = false ) {
if ( ! $user_id || $user_id == get_current_user_id() ) {
$user = wp_get_current_user();
} else {
$user = get_userdata( $user_id );
}
if ( ! $user || ! $user->exists() ) {
return false;
}
if ( is_multisite() ) {
$super_admins = get_super_admins();
if ( ( is_array( $super_admins ) && in_array( $user->user_login, $super_admins ) ) || $user->has_cap( 'delete_users' ) ) {
return true;
}
} else {
if ( $user->has_cap( 'delete_users' ) ) {
return true;
}
}
return false;
}
There is also an alternative solution, which could be more extendable - you can create your own capability and assign it to the Administrator role. That way if for some reason I want to give someone access to all content, but don't want to make them an Administrator on my site, I can just add that particular capability to that particular user(can't find a free plugin at the moment, but there are ways to do it).
This question has decent answers on how to add a custom capability - https://wordpress.stackexchange.com/questions/35165/how-do-i-create-a-custom-role-capability - should you choose to go that way.