Skip to content

Query Users in Carbon Fields Association Field by Role

I have been working on a custom project, a plugin, in which I am using the Carbon Fields library.

In this project I needed to add a field of type “association”, in which I wanted to be able to choose a user and leave it registered in a CPT. That is to say, a field to select a user.

So far so good, as always with Carbon Fields.

I needed to add an assigned consultant to a CPT called Service.

function register_fields()
{
  Container::make('post_meta', esc_html__('Assigned Consultant', 'text-domain'))
    ->where('post_type', '=', 'service')
    ->add_fields(array(
      Field::make('association', 'assigned_consultant', esc_html__('Assigned Consultant', 'text-domain'))
      ->set_types([
        [
          'type'      => 'user'
        ]
      ])
      ->set_max(1)
      ->set_required(true)
    ));
}

add_action('carbon_fields_register_fields', 'register_fields');

The complication is that the user must have a specific role, so I needed to pre-filter the users that Carbon Fields gives me to choose, according to the role I need.

To do this, Carbon Fields allows us to modify the options to modify the query that is performed on the elements of an association type field.

The hook we are interested in is the carbon_fields_association_field_options_{name}_{type} filter.

This hook allows us to change the $options array, which allows us to change the query parameters for the selected types or subtypes.

So, the way to filter by role in an association field for the user type, would be:

function assigned_consultant_field_options($options)
{

  $options['role'] = 'consultant';

  return $options;
}

add_filter('carbon_fields_association_field_options_assigned_consultant_user', 'assigned_consultant_field_options', 10, 1);
Open chat
Escríbenos
How is the plugin of your dreams? :)