I’ve been working on a project lately that makes extensive use of Advanced Custom Fields (ACF) and the post object / taxonomy field types in particular. As my last blog entry outlined, it integrates VERY nicely with the REST API for custom field validation and population. With 50+ fields or sub-fields (in flexible content and repeater fields) on a single custom post type field group, it’s not surprising that conditional logic would be an essential element to show/hide subsets of the field based on user selection. Unfortunately out of box, ACF is limited to choosing select or radio button field types with the conditional logic option.
I asked a question about this to the ACF Support team as there is a long-running forum thread related to this feature / capability / issue:
Is there a method to get conditional logic to support non-select / non-radio-button field types (taxonomy, number, post object, flexible content, repeater, etc)?
Their response gave me an excellent reference point to build out from
Unfortunately, you need to create custom JS code to do that. What you need to do is watching the changed value and then add the selected field with the “hidden-by-conditional-logic” class. To learn how to add JS code for custom fields, please check this page.
As with many development tasks, learning / building the first instance of the solution can be the most time-consuming, so I thought I’d document the exact solution for my use-case here in hopes that it may help others that want to implement conditional logic / validation for (m)any ACF field type.
The High-Level Plan
- Add the class “hidden-by-conditional-logic” to any field you want hidden by default
- Enqueue JS on your admin CPT and/or front-end form
- Use the acf.add_action(‘ready’) function to
- Bind change events matching your field name / type
- Identify the default display state for existing ACF values on page load
- Add_filter for acf/validate_value/name= to ensure required fields that are displayed through this JS-based approach still validate according to conditional logic state.
While it may not be as sexy as the ACF UI approach, it really isn’t too much code. Until a future version of ACF extends conditional display to all field types, this is a quite manageable workaround.