Last updated on September 14, 2023

ACF create_field() function usage

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Understanding ACF create_field() Function.

The create_field() function in Advanced Custom Fields (ACF) is used to create a new field group programmatically. This can be useful when you want to automate the process of creating field groups instead of manually creating them through the ACF interface.

Here’s an example of how to use the create_field() function to create a field group with two fields: a text field and a select field.

function wpsnippets_create_field_group() {
    if( function_exists('acf_add_local_field_group') ) {
        $fields = array(
            array(
                'key' => 'field_text',
                'label' => 'Text Field',
                'name' => 'text_field',
                'type' => 'text',
            ),
            array(
                'key' => 'field_select',
                'label' => 'Select Field',
                'name' => 'select_field',
                'type' => 'select',
                'choices' => array(
                    'option1' => 'Option 1',
                    'option2' => 'Option 2',
                    'option3' => 'Option 3',
                ),
            ),
        );

        $field_group = array(
            'key' => 'group_my_field_group',
            'title' => 'My Field Group',
            'fields' => $fields,
            'location' => array(
                array(
                    array(
                        'param' => 'post_type',
                        'operator' => '==',
                        'value' => 'post',
                    ),
                ),
            ),
        );

        acf_add_local_field_group($field_group);
    }
}
add_action('acf/init', 'wpsnippets_create_field_group');

In this example, we define an array of fields with their respective properties. Each field is represented by an array with keys such as key, label, name, and type. The key is a unique identifier for the field.

We then define a field group array that includes the key, title, fields, and location of the field group. The location specifies where the field group should be displayed, in this case, for the post post type.

Finally, we call the acf_add_local_field_group() function with the field group array to create the field group.

By using the create_field() function, you can easily create field groups programmatically, allowing you to automate the process and save time when working with ACF.

Last updated on September 14, 2023. Originally posted on September 11, 2023.

Leave a Reply