我现在正在使用WordPress高级自定义字段插件:http://www.advancedcustomfields.com/
我在自定义post_type sales_order
上设置了一个中继器字段rows
:
然后,现在使用脚本插入一个帖子:
$post_id = wp_insert_post(array(
'post_title' => $title,
'post_name' => $slug,
'post_content' => $content,
'post_type' => 'sales_order',
'post_status' => 'publish',
));
但是当我这样做时:
update_field('rows', array(), $post_id);
它没有效果。
但是,如果我先在管理面板中手动保存帖子,然后调用update_field
方法,它就可以工作。
所以,我试图窥探wp_postmeta
数据库表,我发现如果我使用脚本调用wp_insert_post
,该帖子不会生成元
| meta_key | meta_value |
|----------|---------------------|
| _rows | field_568e7aeb22714 |
正确。
但是我必须使用纯脚本执行导入工作流,我该如何解决此问题?
您正在传递field_name
但update_field
需要field_key
,如文档所述update_field
考虑这个例子
update_field('field_568e7aeb22714', array(), $post_id);
最后我根据来源做了一个解决方案。
原因:
为什么以下操作失败?
update_field('rows', array(), $post_id);
现在我们使用的是字段名称,而不是字段键。
在这种情况下,ACF 将执行以下操作:
- 尝试查找当前具有
meta_key
:_rows
的帖子元,该元在字段名称之前加上下斜杠。 - 之后,得到那个
meta_value
,它应该是一个字段键,其形式类似于field_XXXXXXX
- 使用已建立的field_key更新字段。
现在我们知道,如果我们以这种方式wp_insert_post
,_rows
元 没有产生正确的meta_value
.
因此,如果我们在管理面板中更新帖子,则提交字段键并生成正确的meta_value
。
结论:只有元值才重要。
溶液:
因此,实际上,我们唯一应该做的更多事情是设置在ACF字段中定义的meta_values绑定到指定post_type
。
下面的例程解决了这个问题:
// The current post_type to search
$post_type = 'sales_order';
$post_id = wp_insert_post(array(
'post_title' => $title,
'post_name' => $slug,
'post_content' => $content,
'post_type' => $post_type,
'post_status' => 'publish',
));
foreach (get_posts(array('post_type' => 'acf', 'posts_per_page' => -1)) as $acf) {
$meta = get_post_meta($acf->ID);
$rule = unserialize($meta['rule'][0]);
if($rule['param'] == 'post_type' &&
$rule['operator'] == '==' &&
$rule['value'] == $post_type) {
foreach($meta as $key => $field) {
if(substr($key, 0, 6) == 'field_') {
$field = unserialize($field[0]);
update_post_meta($post_id, '_'.$field['name'], $key);
}
}
}
}
请注意,我们遍历所有定义的 ACF 帖子,并检查rule
元,以确认它是否绑定在指定的post_type
上。
如果是这样,循环所有以 field_
开头的 ACF 元,并在当前帖子上设置元。
全部完成。
$i = 0; //for metakey
$j=0; //files Count
foreach($files as $fileid){
$j++;
$meta_key = 'files_'.$i.'_file';
//"files" repeater main name and "file" subname ;
update_post_meta($post_id,$meta_key,$fileid);
$i++;
}
update_post_meta($post_id,'files',$j);