phpwordpressadvanced-custom-fields

How to programmatically add an ACF group to the backend of Wordpress?


I've tried a bunch of different functions and approaches but so far I haven't been able to get it working. The goal is to add an Advanced Custom Field group to the backend of Wordpress with some PHP-code. In the best scenario we add the PHP-code to a method of a class.

public function create_group( $group_name ) {

    if ( $this->does_group_already_exists( $group_name ) ) {
        return false;
    }

    acf_add_local_field_group( array(
        'key'      => 'group_1',
        'title'    => 'My Group',
        'fields'   => array(
            array(
                'key'   => 'field_1',
                'label' => 'Sub Title',
                'name'  => 'sub_title',
                'type'  => 'text',
            )
        ),
        'location' => array(
            array(
                array(
                    'param'    => 'post_type',
                    'operator' => '==',
                    'value'    => 'post',
                ),
            ),
        ),
    ) );

    return true;
}

Nothing gets added with the code above. I also tried adding it to functions.php and it with a add_action() function like so:

add_action( 'acf/init', array( $this, 'create_group' ) );

But again, no results.

Hope some one can share a working solution.


Solution

  • Today I finally discovered a solution for adding a ACF group to the backend dynamically with PHP-code.

    It can be done by adding a new post directly with the acf-field-group post type. Here is my implementation for those awesome people from the future that are interested:

    public function create_form( $form_name ) {
    
        $new_post = array(
            'post_title'     => $form_name,
            'post_excerpt'   => sanitize_title( $form_name ),
            'post_name'      => 'group_' . uniqid(),
            'post_date'      => date( 'Y-m-d H:i:s' ),
            'comment_status' => 'closed',
            'post_status'    => 'publish',
            'post_type'      => 'acf-field-group',
        );
        $post_id  = wp_insert_post( $new_post );
    
        return $post_id;
    }
    

    Where $form_name is the name of the ACF group. It works. And there was no need for using a specific hook. I could just call this method directly.