WordPress Logo

Dynamically populating ACF Checkbox Field from Custom DB Query

ACF (Advanced Custom Fields), the greatest WordPress plugin on Earth allows us do some many things. Every time I work on a new project, which I always use ACF, I find a new use or something new the plugin can do. This time there was no exception. I needed to query a custom database table and then display these options/values in an ACF checkbox field which were attached to a Custom Post Type. So I jumped over to the ACF documentation and found this snippet of information for the acf-load_value Filter which Elliot so kindly created for us to alter a fields data.

https://www.advancedcustomfields.com/resources/acf-load_value/

If you do not understand or know what WordPress Filters are continue reading or you can skip down to just view the sample code below. WordPress has Hooks where developers can hook into the code base without having to edit/hack the core code base. There are two types of WordPress hooks, Actions and Filters. From the WordPress Codex, Action Hooks are triggered by specific events that take place in WordPress, such as publishing a post, changing themes, or displaying an administration screen. An Action is a custom PHP function defined in your plugin (or theme) and hooked, i.e. set to respond, to some of these events. Filter hooks are functions that WordPress passes data through, at certain points in execution, just before taking some action with the data (such as adding it to the database or sending it to the browser screen). Filters sit between the database and the browser (when WordPress is generating pages), and between the browser and the database (when WordPress is adding new posts and comments to the database); most input and output in WordPress passes through at least one filter. WordPress does some filtering by default, and your plugin can add its own filtering. So WordPress has its own Hooks and usually good WordPress developers create custom Hooks in their plugins for other developers to use.

So using the acf-load_value filter, I can query the Database, get my result sets and inject these values into my ACF field.


function acf_load_routes_effected_field_choices( $field ) {
	global $wpdb;
	$routes = $wpdb->get_results( "SELECT * FROM shipping_routes" );
	$field['choices'] = array();
    if($routes){        
        foreach( $routes as $route_value ) {       
            $field['choices'][ $route_value->route_id ] = $route_value->route_short_name.' / ' .$route_value->route_long_name;
        }
    }
    return $field;
}
add_filter('acf/load_field/name=routes_effected', 'acf_load_routes_effected_field_choices');

 

Blog, PHP, WordPress,