Conditional logic with Taxonomies (ACF)

If you use the plugin Advanced Custom Fields a lot, like I do you’re bound to run into some sort of limitation.

The problem

My problem (and so it seems, not just mine) was related to taxonomy and conditional logic. While building a site with profiles (with the use of an ACF form), I had a form where profile info had to be entered. For sex I had created a taxonomy, so I added it as a taxonomy field.

And then I ran into this issue. When sex is set to male, there’s no need for info such as cup size and thus I wanted to hide certain fields. And therein lies the problem. With a taxonomy field, there is no conditional logic option. So I had to find another way to solve this.

The solution

The solution was luckily very simple. I created a select field with the options for sex. Make sure the values in the select options correspond with the term ids in your taxonomy !!!

Fortunately there aren’t that many, but in case you have a lot of taxonomy terms you might want to look into dynamically populating select options.

acf/save_post

Ok, now we have our taxonomy and a select field, with options which correspond to the taxonomy ids. Now we need to ‘connect’ them. We do this with the function acf/save_post().

This function runs directly before or after a post is saved in the database. In this case we want to hook after a value has been saved. When a post is saved, the value from the newly created select is stored, which is in fact the term id from the taxonomy we want to store.

We then compare the stored value with the submitted value and if they’re different we know we need to update the post terms.

Working code

Note

  • This example is set to change 1 value only. If you want to change multiple taxonomies, the function needs to be adapted.
  • Please test this on a local/test environment first before putting it live.

Read the entire forum topic here.

Update: there’s now also a plugin which does the trick.