php - 如何以编程方式将 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 组的名称在哪里。有用。并且不需要使用特定的钩子。我可以直接调用这个方法。
推荐阅读
- html - 如何使用 Selenium 自动化 ReactJS 可创建的下拉字段
- angular - 如何显示反应式表单验证错误消息
- java - 基于Java中的URL扩展检查文件类型
- javascript - 在另一个函数中使用时变量可能未定义(Typescript“错误 TS2532)
- react-native - 更改节点模块库
- sql-server - 使用位域和全文搜索查询非常慢
- javascript - 如何为在 JS 的主开发中的任何子 div 中拖放的任何项目触发放置事件
- css - 如何避免 dompdf 中的分页符
- react-navigation - React Navigation - DrawerNavigator 内的 TopTabNavigator
- angular - 如何正确转义 ngstyle 背景图像