首页 WordPress函数大全 update_sub_field()

update_sub_field()

2020-06-28 / 2158阅 / 悠然

如何你看完本文还不知道如何使用该函数,可以联系我定制视频教程,50元/个函数,学不会全额退款

本视频需要登录以后才能播放

登录

描述

更新特定子字段的值。

此功能可以在have_rows()循环内部或外部使用。在内部使用时,当前行将用于更新子字段值。在外部使用时,必须指定行和父对象以定位正确的值位置。

参量

update_sub_field($selector, $value, [$post_id]); 
  • $selector (字符串|数组) (必需) 子字段名称或键,或祖先和行号的数组。
  • $value (混合) (必需) 新值。
  • $post_id (混合) (可选) 保存值的帖子ID。默认为当前帖子。

返回

(布尔)成功更新为true,失败更新为false。

变更记录

  • 在版本5.0.0中添加

例子

更新have_rows()循环内的子字段

本示例说明如何循环使用Repeater字段并使用当前行号更新其子字段值之一。

if( have_rows('repeater') ) {
    $i = 0;
    while( have_rows('repeater') ) {
        the_row();
        $i++;
        update_sub_field('caption', "This caption is in row {$i}");
    }
} 

更新have_rows()循环外的子字段

本示例说明如何在have_rows()循环外部更新子字段值。在此,为$selector参数提供了一个包含字段名和行号混合的数组。该数组应从左到右读取,父子关系由行号分隔。

请参阅有关索引偏移量的注释。

// Update "caption" within the first row of "repeater".
update_sub_field( array('repeater', 1, 'caption'), 'This caption is for the first row of the repeater!' ); 

更新嵌套子字段

update_sub_field()函数还可用于在have_rows()循环内部和外部定位嵌套子字段。本示例说明如何使用这两种方法更新嵌套子字段函数。

// Loop over parent rows.
if( have_rows('repeater') ) {
    $parent_i = 0;
    while( have_rows('repeater') ) {
        the_row();
        $parent_i++;

        // Loop over child rows.
        if( have_rows('sub_repeater') ) {
            $child_i = 0;
            while( have_rows('sub_repeater') ) {
                the_row();
                $child_i++;

                // Update nested sub field value with reference to both parent and child indexes.
                update_sub_field('sub_sub_field', "This value is for repeater row {$parent_i}, and sub_repeater row {$child_i}");
            }
        }
    }
}

// target a nested sub field directly.
update_sub_field( array('repeater', 1, 'sub_repeater', 2, 'sub_sub_field'), 'This value is for repeater row 1, and sub_repeater row 2!' ); 

笔记

索引偏移

当使用特定的行号作为子字段的目标时,请注意,行号从1开始而不是0。这意味着第一行的索引为1,第二行的索引为2,依此类推。

要从0开始索引,请像这样使用row_index_offset设置。

functions.php

add_filter('acf/settings/row_index_offset', '__return_zero'); 
大家谈论
    我的见解