Filter users in a User-Post Type Relationship
Support › MB Relationships › Filter users in a User-Post Type RelationshipResolved
- This topic has 5 replies, 2 voices, and was last updated 4 years, 1 month ago by
Dragan Marian.
-
AuthorPosts
-
February 21, 2021 at 3:23 AM #24510
Dragan Marian
ParticipantHi. I have created a User / Post Type Relationship using the code below.
I would like to be able to populate the select users list only with users having a certain role.
I have browsed the docs, tried using the query args, but to no prevail.Any suggestions for what I like to achieve?
function stores_to_administrators() { MB_Relationships_API::register([ 'id' => 'stores_to_administrators', 'from' => [ 'object_type' => 'post', 'post_type' => 'store', 'empty_message' => 'No store selected', 'admin_column' => 'after title', 'field' => [ 'max_clone' => 1, ], ], 'to' => [ 'object_type' => 'user', 'field' => [ 'max_clone' => 1, ], ], 'label_from' => 'Administrator', 'label_to' => 'Managed Store', ]); }
February 21, 2021 at 3:33 PM #24514Long Nguyen
ModeratorHi Dragan,
Here is the sample code:
'to' => array( 'object_type' => 'user', 'field' => array( 'max_clone' => 1, 'query_args' => array( 'role__in' => array( 'administrator', 'subscriber' ) ) ) ),
Get more details on this documentation https://developer.wordpress.org/reference/functions/get_users/.
February 21, 2021 at 3:59 PM #24515Dragan Marian
ParticipantThank you! That works!
February 22, 2021 at 12:38 AM #24519Dragan Marian
ParticipantWhile that works, when I am on the user profile, I would like to reflect that behavior here as well.
So, given that I can only add stores to administrators, I would like to only show the Relationship Metabox only for those particular roles.
Is there a way to achieve that?February 22, 2021 at 11:33 AM #24526Long Nguyen
ModeratorHi,
You can check the user role before registering the relationship, for example:
add_action( 'mb_relationships_init', function() { $user = wp_get_current_user(); if ( in_array( 'editor', (array) $user->roles ) ) { MB_Relationships_API::register( [ 'id' => 'posts_to_users', 'from' => array( 'object_type' => 'post', 'post_type' => 'post' ), 'to' => array( 'object_type' => 'user', 'field' => array( 'query_args' => array( 'role__in' => array( 'author', 'subscriber' ) ) ) ), ] ); } } );
Refer to this topic: https://wordpress.stackexchange.com/questions/5047/how-to-check-if-a-user-is-in-a-specific-role
February 22, 2021 at 5:10 PM #24530Dragan Marian
ParticipantThe administrator is the one doing this changes so I'll have to check the profile he's trying to edit, not the current user. Anyway, the example was pretty straight forward. Thank you!
-
AuthorPosts
- You must be logged in to reply to this topic.