首页 > 解决方案 > 如何以编程方式将 ACF 组添加到 Wordpress 的后端?

问题描述

我已经尝试了很多不同的功能和方法,但到目前为止我还不能让它工作。目标是使用一些 PHP 代码将高级自定义字段组添加到 Wordpress 的后端。在最好的情况下,我们将 PHP 代码添加到类的方法中。

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;
}

上面的代码没有添加任何内容。我还尝试将它添加到functions.php它并使用add_action()如下功能:

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

但同样,没有结果。

希望有人可以分享一个可行的解决方案。

标签: phpwordpressadvanced-custom-fields

解决方案


今天我终于发现了一个使用 PHP 代码动态添加 ACF 组到后端的解决方案。

可以通过直接使用acf-field-group帖子类型添加新帖子来完成。这是我为那些对未来感兴趣的人提供的实现:

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;
}

$form_nameACF 组的名称在哪里。有用。并且不需要使用特定的钩子。我可以直接调用这个方法。


推荐阅读