如何以编程方式将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' ) );

但同样,没有结果。

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

今天,我终于发现了一种使用 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_name是 ACF 组的名称。它有效。并且不需要使用特定的钩子。我可以直接调用此方法。

实际上,您可以在WP后端本身中通过ACF创建此类代码(不确定这是否仅适用于ACF Pro(。在"管理员"-">自定义字段"-">"工具"->"导出"->"下"创建 PHP"。生成的代码是编程 ACF 集成的一个很好的起点。

它应该看起来像这样:

acf_add_local_field_group(array(
'key' => 'group_5d146d18eeb92',
'title' => 'My Group Title',
'fields' => array(
array(
'key' => 'field_5d146d1f27577',
'label' => 'My Field Title',
'name' => 'my_field_name',
'type' => 'true_false',
'instructions' => '',
'required' => 0,
'conditional_logic' => 0,
'wrapper' => array(
'width' => '',
'class' => '',
'id' => '',
),
'message' => '',
'default_value' => 0,
'ui' => 1,
'ui_on_text' => '',
'ui_off_text' => '',
),
),
'location' => array(
array(
array(
'param' => 'post_type',
'operator' => '==',
'value' => 'my_custom_post_type',
),
),
),
'menu_order' => 0,
'position' => 'side',
'style' => 'default',
'label_placement' => 'top',
'instruction_placement' => 'label',
'hide_on_screen' => '',
'active' => true,
'description' => '',
));

查看 ACF 页面,了解如何通过 PHP 注册字段。

Actionacf/init仅适用于专业版,也许这就是它一开始不起作用的原因。

对于基本版本,您必须使用acf/register_fields来注册自定义字段。

最新更新