php - WC_Order->get_items() 返回空项目

标签 php wordpress woocommerce orders woocommerce-subscriptions

使用钩子(Hook)'woocommerce_order_status_completed'我可以获取$order_id,然后使用$order = wc_get_order($order_id)获取WC_Order对象。但以下 $logger->add("send-order-debug", json_encode($order->get_items()) 返回空项目对象

{"257":{},"258":{},"259":{}}

我不知道为什么会发生这种情况,因为我可以从 woocommerce 订单页面看到该订单中有实际商品。有人知道发生了什么事吗?

我的最终目标是过滤掉“订阅”类别的产品,但如果我不能执行$item->get_product_id,这是不可能的

function send_order($order_id) {
    $order = wc_get_order($order_id);
    $logger = wc_get_logger();
    $logger->add("send-order-debug", json_encode($order->get_items()));
}

订单对象的内容:enter image description here

最佳答案

更新1:

You can't use json_encode() on $order->get_items() as you will always get something like "257":{} (where 257 is the item ID) for each order item. So json_encode() fails encoding each order item data located in the array of items, as order items are protected.

Now the only way to JSON encode order items is to unprotect each order item using the WC_Data method get_data() and set it back in the order items array.

这可以通过使用 array_map() 和自定义函数以紧凑的方式完成,例如:

add_action( 'woocommerce_order_status_completed', 'send_order', 10, 2 );
function send_order( $order_id, $order ) {
    // Unprotect each order item in the array of order items
    $order_items_data = array_map( function($item){ return $item->get_data(); }, $order->get_items() );

    $logger = wc_get_logger();
    $logger->add("send-order-debug", json_encode($order_items_data));
}

现在可以了。


原始答案:

WC_Order 对象已经是 woocommerce_order_status_completed Hook 中包含的参数,因此在您的代码中它应该是:

add_action( 'woocommerce_order_status_completed', 'send_order', 10, 2 );
function send_order( $order_id, $order ) {
    $order_items = $order->get_items();
}

这有效......请参阅 this related answers threads ...

因此,问题可能与您尝试使用以下方式发送订单商品的方式有关:

$logger->add($TAG, json_encode($order->get_items()));

But it's not possible to help as your code is not testable: the $logger and $TAG variables are not defined in your code.

现在要定位订阅产品,您将使用以下内容:

// Loop through order items
foreach( $order->get_items() as $item ) {
    $product = $item->get_product(); // get the WC_Product Object
    
    // Targeting subscription products only
    if ( in_array( $product->get_type(), ['subscription', 'subscription_variation'] ) ) {
        // Do something
    }
}

关于php - WC_Order->get_items() 返回空项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62415821/

相关文章:

wordpress - 采用 Google Adsense 收入分配模型的网站

php - 是否可以使用 woocommerce 将数据保存到两个数据库?

PHP SoapClient 删除字段?

javascript - 验证 WordPress 简单工作板插件中的文本字段内容

php - 如何将查询结果存储到 mysql 中的变量中,然后将其用于另一个查询和回显结果?

javascript - Wordpress - 单击时自动关闭移动菜单

wordpress - 在产品页面上禁用 WooCommerce SKU

php - WooCommerce前端产品创建

php - 如何根据表的大小动态设置分页符?

PHP:可以自动获取所有发布的数据吗?