Support Forum
Support › MB Relationships › Filter users in a User-Post Type RelationshipResolved
Hi. 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',
]);
}
Hi 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/.
Thank you! That works!
While 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?
Hi,
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
The 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!