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

WooCommerce get_items()返回空数组,如何在JS中处理订单商品?

解决WooCommerce订单商品列表无法正确JSON序列化的问题

问题原因

$order->get_items()返回的是WC_Order_Item_Product对象集合,这类对象是WooCommerce封装的实例,内部包含私有/受保护属性,直接用json_encode()无法解析这些属性,因此只会输出以商品ID为键的空结构。

解决方法

需要手动遍历商品项,提取你需要的字段组装成普通PHP数组,再转成可被JS识别的JSON格式。以下是修改后的完整代码:

add_action( 'wp_head', 'function_after_order' );
function function_after_order() {
    if ( ! is_wc_endpoint_url('order-received') ) return;
    global $wp;

    if ( isset($wp->query_vars['order-received']) && absint($wp->query_vars['order-received']) > 0 ) :
        $order_id = absint($wp->query_vars['order-received']);
        $order = wc_get_order($order_id);
        $order_items = [];

        // 遍历每个订单商品项
        foreach ( $order->get_items() as $item_id => $item ) {
            // 获取对应的商品对象
            $product = $item->get_product();
            
            // 提取需要的字段,可根据需求增减
            $order_items[] = [
                'item_id'    => $item_id,
                'product_id' => $item->get_product_id(),
                'name'       => $item->get_name(),
                'quantity'   => $item->get_quantity(),
                'subtotal'   => $item->get_subtotal(),
                'total'      => $item->get_total(),
                'price'      => $product ? $product->get_price() : 0,
                'sku'        => $product ? $product->get_sku() : ''
            ];
        }

        // 使用wp_json_encode处理,比原生json_encode更适配WordPress环境
        $items_json = wp_json_encode($order_items);
        ?>
        
        <script type="text/javascript">
            // 解析JSON字符串为JS对象
            const orderItems = JSON.parse('<?php echo $items_json; ?>');
            console.log('订单商品列表:', orderItems);
            
            // 示例:遍历处理每个商品
            orderItems.forEach(item => {
                console.log(`商品:${item.name},数量:${item.quantity},总价:${item.total}`);
            });
        </script>
        <?php
    endif;
}

关键说明

  • 用wp_json_encode()替代原生json_encode():自动处理WordPress环境下的字符编码、转义问题,避免JSON格式错误。
  • 按需提取字段:代码中列出的是常用字段,你可以根据需求添加商品图片链接、自定义属性等,通过$product或$item对象的对应方法获取即可。
  • JS端解析:通过JSON.parse()将字符串转为JS对象,方便后续遍历、操作商品数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:30:57