WooCommerce Bookings 前端更新产品定价元数据存储格式异常求助
问题根因
你遇到的问题核心是PHP数组构造语法错误,同时没有对齐原有存储的数组结构:
- 原有
_wc_bookings_pricing的存储结构是「外层为长度1的索引数组,索引0对应的元素是包含7个键值对的关联数组」 - 你当前写的
array('type', $type, 'cost', $cost...)是把键名和值都作为独立的索引数组元素存入,自然会生成14个元素的错误结构 - 额外注意:原有存储的键名为
modifier/base_modifier,你代码里拼写为modifyer多了字母y,会导致后续WooCommerce读取字段异常
修正后代码
如果你的需求是覆盖现有的第一条定价规则,直接用以下代码即可:
$type = isset($_POST['input_1']) ? $_POST['input_1'] : null; $cost = isset($_POST['input_25']) ? $_POST['input_25'] : null; // 修正拼写错误,和原有键名对齐 $modifier = isset($_POST['input_20']) ? $_POST['input_20'] : ''; $base_cost = isset($_POST['input_24']) ? $_POST['input_24'] : null; $base_modifier = isset($_POST['input_20']) ? $_POST['input_20'] : ''; $date_from = isset($_POST['input_2']) ? $_POST['input_2'] : null; $date_to = isset($_POST['input_3']) ? $_POST['input_3'] : null; // 修正数组结构:外层索引数组 + 内层关联数组,使用 键=>值 语法构造关联数组 $response = [ 0 => [ 'type' => $type, 'cost' => $cost, 'modifier' => $modifier, 'base_cost' => $base_cost, 'base_modifier' => $base_modifier, 'from' => $date_from, 'to' => $date_to ] ]; update_field('_wc_booking_pricing', $response, 379);
追加定价规则的补充写法
如果你的需求是新增一条定价规则而不是覆盖已有规则,可以先读取原有值再追加新元素:
// 先读取已有定价规则 $existing_pricing = get_field('_wc_booking_pricing', 379) ?: []; // 构造新规则 $new_pricing = [ 'type' => $type, 'cost' => $cost, 'modifier' => $modifier, 'base_cost' => $base_cost, 'base_modifier' => $base_modifier, 'from' => $date_from, 'to' => $date_to ]; // 追加新规则到原有数组 $existing_pricing[] = $new_pricing; // 写回数据库 update_field('_wc_booking_pricing', $existing_pricing, 379);
内容的提问来源于stack exchange,提问作者Eric Brockman
相关产品推荐
相关产品推荐

