Written July 17, 2012.
Tagged #Advanced Custom Fields, #Conditional Logic, #jQuery
Currently in version 3.3.1, the Advanced Custom Fields plugin does not provide an interface for creating condition logic rules for fields. However, this functionality can be easily created with just a small amount of jQuery code. Check out the video to view the end result!
1. Creating the fields
In this short tutorial we will create a field group with 4 fields and add them to all pages (via the location rules). These fields are:
- Hero Type – A dropdown to select what kind of “Hero” element to use on the page. This will act as the switch for the conditional logic
- Hero Image – An image field that will show when “Image” is selected by “Hero Type”
- Hero Video – A textarea field that will show when “video” is selected by “Hero Type”
- Hero Slider – A gallery field that will show when “slider” is selected by “Hero Type”
2. Adding the code
The Advanced Custom Fields plugin makes it very easy to add scripts and styles to the edit screens within WordPress. All you need to do is create a function and attaching it to the action acf_head-input. This will run in the head of any page where ACF generates input fields. Read more about ACF’s hooks and filters here.
The following code should be placed in your functions.php file within your active theme.
That's it! Obviously you will need to edit the code to work with the fields that you have, but this will not take long (if you use either firebug or inspector to view html / console logs).
Soon, I plan to add an interface into ACF to do all this for you, but for now, this is the easiest way to add conditional logic to your fields.