The WordPress plugin Advanced Custom Fields or Advanced Custom Fields Pro (ACF) is a great help when it comes to building simple or complex input masks. An important detail here is the option to define input fields as mandatory fields. This prevents certain important information from being missing. In a custom post type (CPT) of the calendar type, for example, this could be the event location or the organizer’s email address.
On the other hand, mandatory fields can also be annoying. Sometimes you want users of a certain role (e.g. ‘organizer’) to have to fill in these fields in order to be able to save a new entry – but for other user roles (e.g. ‘editor’) this information may not be available at all.
So how do you make these input fields mandatory for certain roles, but optional for other roles? This is where the “prepare_field” filter comes in handy. This allows us to interpose ourselves, so to speak, in the process that creates the input field.
In order to achieve a unique assignment of a specific input field, we address the key of the field – here in the example the field ‘Venue’ with the imaginary key “field_123”.
// Location * add_filter('acf/prepare_field/key=field_602bbd380ae1b', 'custom_submission_required_fields1'); function custom_submission_required_fields1($field) { $field['required'] = true; $user = wp_get_current_user(); if (( in_array( 'redaktion', (array) $user->roles ) ) || ( in_array( 'administrator', (array) $user->roles ) )) { // if (is_admin()) { $field['required'] = false; } return $field; }
In the code snippet above, we first specify that the field is a mandatory field – i.e. ‘required’. In the next step, we use the wp_get_current_user function to query the user role of the current user. If the user now belongs to the Editor or Administrator role, we remove the “mandatory field” setting again. This means that users with the Editorial role and site administrators can create new entries of the event type without having to fill in the ‘Event location’ field. However, all other users (e.g. organizers) can only save (or submit) new entries if they have filled in the ‘Event location’ field.
The code snippet must of course be copied back into the functions.php of the active theme. And for the switch to work, the field in ACF must be defined as a not-required field.
Mandatory field optional per role in the frontend form
Of course, this mandatory field switch also works for frontend forms. The fields are marked as mandatory fields according to the design defined in the theme (usually with the small red asterisk) and the standard warning for mandatory fields also appears as expected, as is usual for normal mandatory fields in the design of the theme used.