我用它成功地插入了带有ACF/Posteta数据的帖子,但请在部署live之前在开发站点上测试它,可能会有一些可怕的假设。通常,它假设每个名称只有一次,即“myfield”不存在于两个含义不同的字段组中。
$mycustomvalue = 123;
$f_mycustomfield = get_acf_key_by_name("mycustomfield");
update_post_meta( $postid, "mycustomfield", $mycustomvalue );
update_post_meta( $postid, "_mycustomfield", $f_mycustomfield["key"] );
function load_acf_names2key() {
global $acf_names2key;
$acf_names2key = array();
$posts = get_posts(array(
\'numberposts\' => -1,
\'post_type\' => \'acf\',
\'orderby\' => \'menu_order title\',
\'order\' => \'asc\',
\'suppress_filters\' => false,
));
foreach($posts as $fieldgroup) {
$fields = get_post_meta( $fieldgroup->ID );
foreach($fields as $fieldkey => $fieldmeta) {
if(substr($fieldkey, 0, 6) == "field_") {
$field = get_post_meta( $fieldgroup->ID, $fieldkey);
foreach($field as $subfield) {
if(!array_key_exists($subfield["name"], $acf_names2key)) $acf_names2key[ $subfield["name"] ] = array();
$subfield[ "group" ] = $fieldgroup->post_name;
array_push( $acf_names2key[ $subfield["name"] ], $subfield );
}
}
}
}
}
function get_acf_key_by_name($name, $options = array()) {
global $acf_names2key;
if(!$acf_names2key || !is_array($acf_names2key) || count($acf_names2key) == 0) {
load_acf_names2key();
}
if(!array_key_exists($name, $acf_names2key))
return false;
foreach($acf_names2key[ $name ] as $possible) {
foreach($options as $key => $val) {
if(preg_match("!^/.*/i?$!", $val)) {
if(!preg_match($val, $possible[ $key ])) {
continue 2;
}
}
else if($possible[ $key ] != $val) {
continue 2;
}
}
# no options? this will return the first one
# has options? will return the first item that
# satisfies all options
return $possible;
}
return false;
}
我写这篇文章已经有很长一段时间了,但我记忆犹新,我到底想用那些可以传递给的$选项做什么
get_acf_key_by_name
(或者如果我只是从某处复制粘贴的代码),但它总是对我有用。我还没有尝试使用转发器字段,所以这可能是一个挑战,但请尝试一下。