updat_field不适用于高级自定义域的后对象


updat_field not working for advanced custom field 's postobject

我有帖子对象,需要根据我正在使用的文本进行设置或更新 update_field 但它不会更新帖子中帖子对象的选定值

<?php
$allposts= get_posts(array('post_type' => 'genres', 'numberposts' => -1));
$newgenre="MYSTERY";
foreach ( $allposts as $post ) :  setup_postdata($post);
if (!empty($post))
    {
    update_field('genrelist',$newgenre,$post->ID);  
    }
endforeach;
?>

你写出的内容,虽然性能不如你想象的,但应该基于update_field()文档工作。您可以考虑尝试以下操作:

  • 验证"流派列表"是否为自定义字段正在使用的元键
  • 尝试将"genrelist"换成字段键(有关如何显示此内容的说明,请参阅"[查找字段键](http://www.advancedcustomfields.com/resources/update_field/#finding-字段键)"以确保它不是引用查找问题。
  • 您对get_posts的调用是将帖子类型设置为"流派",但这似乎更有可能是分类法而不是自定义帖子类型。您可能需要验证 $allposts 是否没有为您提供空数组(这意味着永远不会执行具有update_field()调用的 foreach 循环)。

无论它的价值如何,由于您没有在提供的代码中使用get_the_ID()等函数,因此您无需担心setup_postdata()。检查empty()似乎也没有必要,因为get_posts()不应该返回空帖子。重写后,示例代码更像这样:

$allposts = get_posts( array( 'post_type' => 'genres', 'posts_per_page' => 100 ) );
$newgenre = 'MYSTERY';
foreach ( $allposts as $single_post ) {
  update_field( 'genrelist', $newgenre, $post->ID );
}

FWIW,如果您的网站有很多帖子,numberposts/posts_per_page设置为"-1"可能是一个巨大的性能问题。最好设置一个合理的上限(在重写的代码中,我使用了 100,但您的限制可能会有所不同)。有关更多信息,10up已经开源了WordPress开发的最佳实践(完全披露:我为10up工作)。