updat_field不适用于高级自定义字段的postobject

时间:2015-01-14 14:21:52

标签: php advanced-custom-fields

我有帖子对象需要根据文本使用 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;
?>

1 个答案:

答案 0 :(得分:1)

你已写出来的内容虽然效果不如你想象的那么高, 应该基于the update_field() documentation开展工作。您可以考虑尝试以下方法:

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

无论它有什么价值,因为您未在您提供的代码中使用get_the_ID()等功能,您不必担心{{1 }}。对setup_postdata()的检查似乎也没有必要,因为empty()不应该返回空帖。重写,示例代码更像是这样:

get_posts()

FWIW,将$allposts = get_posts( array( 'post_type' => 'genres', 'posts_per_page' => 100 ) ); $newgenre = 'MYSTERY'; foreach ( $allposts as $single_post ) { update_field( 'genrelist', $newgenre, $post->ID ); } 设为等于&#39; -1&#39;如果您的网站有很多帖子,则可能是一个巨大的性能问题。设置合理的上限更好(在重写的代码中,我使用了100,但你的限制可能会有所不同)。有关更多信息,10up has open sourced their best practices for WordPress development(完全披露:我为10up工作)。

相关问题