name = 'role_selector';
$this->label = __( 'User Role Selector', 'acf-role-selector-field' );
$this->category = __( 'Choice', 'acf' );
$this->defaults = array(
'return_value' => 'name',
'field_type' => 'checkbox',
'allowed_roles' => '',
);
parent::__construct();
$this->settings = array(
'path' => apply_filters( 'acf/helpers/get_path', __FILE__ ),
'dir' => apply_filters( 'acf/helpers/get_dir', __FILE__ ),
'version' => '3.0.0'
);
}
/**
* Field Options
*
* Creates the options for the field, they are shown when the user
* creates a field in the back-end. Currently there are three fields.
*
* The Return Format determines how the value is returned to the front-end.
* Role Name returns just the name, Role Object will grab all data
* associated with the role.
*
* The Allowed Roles field lets users choose which roles may be selected.
* If all or none of the roles are selected all roles will be allowed.
*
* The field type determines how the user can select roles using our field.
* Checkbox and multiselect is available for multiple selections and radio
* buttons and select boxes are available for single selections.
*
* @param array $field The details of this field
* @author Daniel Pataki
* @since 3.0.0
*
*/
function create_options( $field ) {
$field = array_merge( $this->defaults, $field );
$key = $field['name'];
?>
roles;
foreach( $roles as $role => $data ) {
if( is_array( $field['allowed_roles'] ) && !in_array( $role, $field['allowed_roles'] ) ) {
unset( $roles[$role] );
}
}
$roles = apply_filters( 'acfrsf/allowed_roles', $roles, $field );
// Select and multiselect fields
if( $field['field_type'] == 'select' || $field['field_type'] == 'multi_select' ) :
$multiple = ( $field['field_type'] == 'multi_select' ) ? 'multiple="multiple"' : '';
?>
';
foreach( $roles as $role => $data ) :
$checked = ( !empty( $field['value'] ) && in_array( $role, $field['value'] ) ) ? 'checked="checked"' : '';
?>
';
echo '';
endif;
}
/**
* Format Value For API
*
* This filter is appied to the $value after it is loaded from the db
* and before it is passed back to the api functions such as the_field
*
* @param mixed $value The value which was loaded from the database
* @param int $post_id The $post_id from which the value was loaded
* @param array $field The details of this field
* @return mixed $value The modified value
* @author Daniel Pataki
* @since 3.0.0
*
*/
function format_value_for_api($value, $post_id, $field) {
if( $field['return_value'] == 'object' && !empty( $value ) ) {
foreach( $value as $key => $name ) {
$value[$key] = get_role( $name );
}
}
return $value;
}
}
new acf_field_role_selector();
?>