ACF lazy load Select options

Advanced Custom Fields is used a lot by WordPress developers, and it comes with a lot of handy fields. It's also very developer friendly, for example giving the ability to populate a select field through filters. But in some cases you may have a crazy amount of options/choices to populate it with. I recently had this happen on a project, there were about 10.000 options that were loaded from a JSON file.

Things became even worse since it was placed in a repeater. Loading the edit page for that post became wildly slow. Imagine, if the field appeared 4 times, there would be 40.000 lines of html containing the option tags alone. Luckily ACF allows you to load values into the Select field using AJAX if you use the Stylised UI option. Unfortunately it doesn't add much value out of the box and it's not really documented either. In this post, you will see how you can start using it.

Obstacles

If you just want the solution, feel free to skip this part. Now, normally we would use the acf/load_field filters and just add all the choices. Unfortunately though, the AJAX option on the field doesn't make a difference here. It will just add all the options when the field is rendered initially.

Now then, maybe we can limit the choices in the acf/load_field filter by checking if we are in WP_AJAX. Perhaps not even including a single one until the user starts searching. Here came my biggest issue into play, the acf/load_field doesn't yet know the current field value, and if you don't add the current value as an option, the select field will appear blank.

So looking for a different filter, acf/prepare_field came up. At this point the value is loaded, and you can still set the choices. Great, only one issue, during an AJAX request this filter isn't used. Therefore, you still need to use the acf/load_field filter to add the choices to begin with.

Solution

We need to use the acf/prepare_field to limit the results for when the field is rendered. Since this filter doesn't run during AJAX calls, this is all pretty smooth sailing. In addition we have to use the acf/load_field if we want to populate the field with all possible choices. This part is well documented, and with that in place all you need is something like this:

If you want to load values differently check if WP_AJAX is running by using the wp_doing_ajax() function. When searching, the arguments (post_id, search query, etc) are available in the $_POST object.