2020-06-28 / 1915阅 / 悠然
更新特定字段的值。
update_field($selector, $value, [$post_id]);
$selector
(字符串) (必填) 字段名称或字段键。$value
(混合) (必需) 新值。$post_id
(混合) (可选) 保存值的帖子ID。默认为当前帖子。(布尔)成功更新为true,失败更新为false。
本示例说明如何在当前正在查看的帖子上更新名为“ views”的字段的值。
// Get the current value.
$count = (int) get_field('views');
// Increase it.
$count++;
// Update with new value.
update_field('views', $count);
本示例说明如何使用字段的键而不是其名称来获得与上述相同的结果。将新值保存到帖子时(不存在任何值时),应使用字段的键。这有助于ACF在值和字段设置之间创建正确的“引用”。
数据库中保存的每个值都会得到该字段键的“参考”。这允许ACF将值与其字段连接。ACF这样做是为了在加载时可以根据字段类型和设置来格式化值。例如,图像字段包含返回图像数据数组而不是附件ID的设置。
// Get the current value.
$count = (int) get_field('field_123456');
// Increase it.
$count++;
// Update with new value.
update_field('field_123456', $count);
此示例显示了各种$ post_id值,用于更新帖子,用户,术语和选项中的值。
$post_id = false; // current post
$post_id = 1; // post ID = 1
$post_id = "user_2"; // user ID = 2
$post_id = "category_3"; // category term ID = 3
$post_id = "event_4"; // event (custom taxonomy) term ID = 4
$post_id = "option"; // options page
$post_id = "options"; // same as above
update_field( 'my_field', 'my_value', $post_id );
本示例将演示如何创建新帖子,以及如何向其中保存多个字段值。
// Create new post.
$post_data = array(
'post_title' => 'My post',
'post_type' => 'post',
'post_status' => 'publish'
);
$post_id = wp_insert_post( $post_data );
// Save a basic text value.
$field_key = "field_123456";
$value = "some new string";
update_field( $field_key, $value, $post_id );
// Save a checkbox or select value.
$field_key = "field_1234567";
$value = array("red", "blue", "yellow");
update_field( $field_key, $value, $post_id );
// Save a repeater field value.
$field_key = "field_12345678";
$value = array(
array(
"sub_field_1" => "Foo",
"sub_field_2" => "Bar"
)
);
update_field( $field_key, $value, $post_id );
// Save a flexible content field value.
$field_key = "field_123456789";
$value = array(
array( "sub_field_1" => "Foo1", "sub_field_2" => "Bar1", "acf_fc_layout" => "layout_1_name" ),
array( "sub_field_x" => "Foo2", "sub_field_y" => "Bar2", "acf_fc_layout" => "layout_2_name" )
);
update_field( $field_key, $value, $post_id );
如果传递给此函数的值与数据库中已存在的值相同,则此函数返回false。