Site icon Hip-Hop Website Design and Development

ACF: How to get the full field name (meta_key) by a field key?

In Advanced Custom Fields: Which function can I use to get the full meta key of a field by its field key?

So, if I have a field with the name some_field and the field key field_sd54hfs5df: How do I get the name by the key?

I found the function acf_get_fields() and acf_get_field(), but when using field types like group, flexibel_content or repeater the names in the returned arrays are not the full names that are stored in the meta database tables.

For example, when a group has the name some_group and the field some_field the mentioned functions only return some_group or some_field, but not the full meta_key, which is some_group_some_field.

Unfortunately subfields of such a field type are not returned, so I don’t see an option to reformat the returned arrays to combine the arrays recursively to built up the full meta key names.


I have written the below method to fetch the field name as stored under the _some-field… metadata by ACF, but when working in an environment with trash metadata and old records this is fetching multiple records, so that isn’t a solution.

/**
 * Get a meta key name by a ACF field key
 * 
 * @since 1.0.22
 * 
 * @param string $key
 * @return null|string
 */
public function getUserMetaKey(string $key): ?string
{
    global $wpdb;
    $select = "SELECT distinct meta_key FROM $wpdb->usermeta WHERE meta_value = '$key' AND meta_key NOT LIKE 'acfe_form_actions_%'";
    // Debug::log($select);
    $usermeta = $wpdb->get_results($select);
    // Debug::log($usermeta);
    if (count($usermeta) > 0) {
        $metaKey = $usermeta[0]->meta_key;
        $metaKey = ltrim($metaKey, '_');
        return $metaKey;
    }
    return null;
}