You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将WooCommerce订单商品逐行存入ACF Repeater字段并获取下单价格

问题解决方法

现有代码错误点

  • 循环获取订单项数据时,$product变量未初始化,$product->get_price()本身无法正常返回值
  • 即使初始化$product = $item_data->get_product(),获取的是商品当前价格,不是下单时的历史单价,不符合需求
  • $user_ID变量未定义,会导致新建文章的作者字段为空
  • update_field放在循环内重复调用,执行效率低

正确获取下单时单价的两种方案

两种方案返回的都是下单那一刻的历史单价,不会随后续商品售价调整变动:

  1. 通过订单行小计计算(推荐,兼容性最高)
    订单行小计本身就是下单时单价*购买数量的结果,直接计算即可:
$product_prices[] = $item_data->get_subtotal() / $item_data->get_quantity();

如果需要获取含税单价,把get_subtotal()替换为get_total()即可。
2. 直接读取订单项内置元数据
WooCommerce下单时会自动把当时的单价存入订单项的_price元字段,直接读取即可:

$product_prices[] = $item_data->get_meta('_price', true);

修正后的完整代码

// 下单后创建包含订单详情的自定义文章
function create_post_after_order( $order_id ) {
    if ( $order_id instanceof WC_Order ){
        return;
    }
    
    $order = wc_get_order( $order_id );
    $order_items = $order->get_items(); 
    $user_ID = $order->get_user_id(); // 从订单获取用户ID,修复未定义变量问题
    
    // 初始化数组避免PHP警告
    $product_ids = [];
    $product_names = [];
    $product_quantities = [];
    $product_prices = [];
    $ordeline_subtotals = [];
    
    foreach ( $order_items as $item_id => $item_data ) {
        $product_ids[] = $item_data->get_product_id();
        $product_names[] = $item_data->get_name();
        $product_quantities[] = $item_data->get_quantity();
        // 这里可替换为上述两种方案的任意一种
        $product_prices[] = $item_data->get_subtotal() / $item_data->get_quantity();
        $ordeline_subtotals[] = $item_data->get_subtotal();
    }
    
    // 创建自定义文章
    $new_post = array(
        'post_title' => "Order {$order_id}",
        'post_date' => date('Y-m-d H:i:s'),
        'post_author' => $user_ID,
        'post_type' => 'groeiproces',
        'post_status' => 'publish',
    );    
    $post_id = wp_insert_post($new_post);
    
    // ACF字段绑定
    $orderdetails_key = 'field_61645b866cbd6';
    $product_id_key = 'field_6166a67234fa3';
    $product_name_key = 'field_61645b916cbd7';
    $product_quantity_key = 'field_6165bd2101987';
    $product_price_key = 'field_6166a68134fa4';
    $ordeline_subtotal_key = 'field_6166a68934fa5';
    
    // 组装Repeater数据
    $orderdetails_value = [];
    foreach ($product_ids as $index => $product_id) {
        $orderdetails_value[] = array(
            $product_id_key => $product_id, 
            $product_name_key => $product_names[$index],
            $product_quantity_key => $product_quantities[$index],
            $product_price_key => $product_prices[$index],
            $ordeline_subtotal_key => $ordeline_subtotals[$index],
        );
    }
    // 循环外统一更新ACF字段,仅调用一次
    update_field( $orderdetails_key, $orderdetails_value, $post_id );
}
add_action( 'woocommerce_thankyou', 'create_post_after_order', 10, 1 );

内容的提问来源于stack exchange,提问作者Nico Weerheim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 00:39:03