更新 1:
您不能在$order->get_items() 上使用json_encode(),因为对于每个订单商品,您总会得到类似"257":{} (其中257 是商品ID)。因此,json_encode() 无法对位于商品数组中的每个订单商品数据进行编码,因为订单商品受到保护。
现在对订单商品进行 JSON 编码的唯一方法是取消保护每个订单商品,使用 WC_Data 方法 get_data() 并将其设置回订单商品数组中。
这可以使用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 挂钩中包含的参数,因此在您的代码中应该是:
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()));
但由于您的代码不可测试,因此无法提供帮助:$logger 和 $TAG 变量未在您的代码中定义。
现在要定位订阅产品,您将使用以下内容:
// 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
}
}