WordPress: ACF Data Selector field

2 min read wordpress

On a recent WordPress build I needed to allow the client to select ranges of custom data. I’m a big fan of Advanced Custom Fields so decided to modify the relationship field to allow it to accept custom data instead of custom post types, I call it the Data Selector field.

After downloading the plugin from the Github repository and enabling it within WordPress we need to set some custom data sets, we do this be utilising the acf_data_selector/data action:

add_action('acf_data_selector/data', function($data) {

$data['countries'] = array(
'label' => 'Countries',
'data' => array(
'US' => 'United States',
'UK' => 'United Kingdom'
)
);

$data['rooms'] = array(
'label' => 'Rooms',
'data' => array(
'101' => array(
'label' => 'Meeting Room',
'room_number' => '101',
'floor' => '1',
'telephone' => '100'
),
'102' => array(
'label' => 'Stock Room',
'room_number' => '102',
'floor' => '1',
'telephone' => '102'
),
'202' => array(
'label' => 'Manager Room 1',
'room_number' => '202',
'floor' => '2',
'telephone' => '202'
),
)
);

$data['regions'] = array(
'label' => 'Regions',
'data' => json_decode(file_get_contents('/data/regions.json'), TRUE)
);

return $data;

});

With this action we’re passed the $data array of which we can add data sets to. In the example above we add various example data sets:

  • Countries
    • Uses basic array
    • Value (string) used for both the UI label and response from get_field()
  • Rooms
    • Uses complex array
    • Array value label used for UI, entire array returned for get_field()
    • Very handy to provide back related data
  • Regions
    • Uses data from a JSON file, in any of the above formats

You could of course get data from other sources, just as long as it uses the array formats above.

Now the data sets have been registered we can go and add the field within a field group:

Data Selector, Field Group

Simply select the “Data Selector” field type then select the data set you registered earlier. After saving the field will appear in the post edit screen, it takes the very same form of the relationship field:

data-selector-example

Selecting data works exactly like the relationship field, searching is available to. In the example above we’ve selected the “Meeting Room” and “Stock Room” values, when using get_field() on this field the output is as follows:

array(
array(
'label' => 'Meeting Room',
'room_number' => '101',
'floor' => '1',
'telephone' => '100'
),
array(
'label' => 'Stock Room',
'room_number' => '102',
'floor' => '1',
'telephone' => '102'
)
)

And that’s the Data Selector field, based on the fantastic Advanced Custom Fields plugin for WordPress, this plugin allows selecting ranges of custom data quickly and easily.

Comments and feedback greatly appreciated, issues on Github.

https://github.com/theideabureau/acf-data-selector-field