Support

Account

Home Forums General Issues Add all fields for a field group via code on object creation Reply To: Add all fields for a field group via code on object creation

  • I’ve implemented this – be interested to get your opinion or is there’s a better way of doing it

    This function returns an associative array given a Field Group title. The array keys are the field name slugs, and the array values are the field keys.

    function get_acf_field_keys($field_group_title) {
    
            global $wpdb;
    
            // get the post id for this field group
            $sql = $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = '%s' AND post_type = 'acf'", $field_group_title );
            $field_group_id = $wpdb->get_var($sql);
    
            // now get all postmeta items (the fields in the fieldgroup) for that postid
            $sql = $wpdb->prepare(" SELECT meta_value from $wpdb->postmeta
                                    WHERE post_id = '%d' AND meta_key LIKE 'field%%'",$field_group_id);
            $acf_postmeta_fields = $wpdb->get_results($sql);
    
            $fields = array();
            foreach ($acf_postmeta_fields as $acf_postmeta_field) {
                $unserialized = unserialize($acf_postmeta_field->meta_value);
                $fields[$unserialized['name']] =  $unserialized['key'];
            }
            return $fields;
        }