Get an ACF sub-field key by field name

Having written plugins that extend the very popular WordPress plugin Advanced Custom Fields (ACF), I’ve come up against the need to work out a field’s key based on its field name.

This normally comes up when structuring data for programmatic field update as ACF needs to the values mapped to field keys when updating complex fields such as repeaters, flexi-fields, etc.

A function for finding a sub-field key based on its field name

If you find yourself needing to update a complex field using ACF’s built-in update_field() function, you should find the following to be quite useful.

<?php
/**
* Locates an ACF sub-field by field name and returns the sub-field's key.
*
* This is particularly useful if you need to construct a data array for programmatic field
* update where a complex field is in use (e.g; repeater, group, flexi).
*
* @param string $sub_field_name The sub field name we need a key for.
* @param array $field The ACF field array.
*
* @return string The sub-field's field key or an empty string where the sub-field is not found
*/
function get_acf_sub_field_key_by_field_name( $sub_field_name, array $field ) {
$sub_fields = acf_get_fields( $field );
foreach ( $sub_fields as $sub_field ) {
if ( $sub_field['name'] === $sub_field_name ) {
return $sub_field['key'];
}
}
return '';
}

Need a website? 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.