Load an ACF field’s options dynamically via PHP.

One thing I really appreciate about the Advanced Custom Fields (ACF) plugin is the flexibility it offers via WordPress’ hook system. For most use cases, we can do what we need from the admin but now and then I come up against scenarios where it is either necessary or just a whole lot easier to set things up via PHP.

One such example of this is dynamically loading options on a select/radio/checkbox field. We can obviously just type in any number of options in the field’s settings but there are definitely times where it’s just way more sensible to load them in via PHP – take a full list of countries of the world, for example. That’s a big list… I sure as shit ain’t typing it.

Another perk to loading the field’s options via PHP is that they can’t actually be changed in the WordPress admin. This can be very useful if you need to lock down those options.

Use ACF’s acf/load_field hooks to dynamically load field options

Here’s a quick look at an example of loading up a custom set of options via PHP. In this example, we’re targeting a specific field by field name.

<?php
add_filter( 'acf/load_field/name=countries', function ( $field ) {
$field['choices'] = [
'au' => 'Australia',
'nz' => 'New Zealand',
'gb' => 'United Kingdom',
'us' => 'United States',
// …
];
return $field;
} );

The acf/load_field hook and its variations is a very convenient and powerful point of extension. You could pull key-value pairs from PHP files, JSON files, a database, an API, or wherever you like.

If you haven’t already read it, ACF’s document on the filter is a very nice reference and will teach you more about the hook variations that are available.

Got a project? Let's talk.

From website design & SEO through to custom WordPress plugin development. I transform ideas into dynamic, engaging, and high-performing solutions.
Subscribe to get the latest insights & updates in the world of web and how it impacts your business and website.
© 2024 Phil Kurth  |  All rights reserved.