在 null 上调用成员函数 get_cart_contents_count()

Call to a member function get_cart_contents_count () on null

我修改了 email-order-details.php 代码,使其能够包含商品总数。

echo WC()->cart->get_cart_contents_count();

除一种情况外,这很有效。

当我修改几个项目时,例如通过从后端更改状态,我收到以下错误:

致命错误:调用成员函数 get_cart_contents_count () on null in email-order-details.php on line 61

批量版为什么会出现这个错误?有办法解决吗?

谢谢!

暂时解决了:

if ( is_null(WC()->cart) ) {} else { echo WC()->cart->get_cart_contents_count(); }

您也可以使用此行 (因为 WC()->cart 是实时 WC_Cart 实例对象)

echo is_object( WC()->cart ) ? WC()->cart->get_cart_contents_count() : '';

应该也可以。


现在对于电子邮件,可能您的目标是 "Order items" 而不是 。如果是这种情况,您将需要获取 WC_Order 对象……如果没有,您可以从订单 ID 中获取……

// If the WC_Order object doesn't exist but you have the Order ID
if( ! ( isset( $order ) && is_object( $order ) ) && isset( $order_id ) ){
    // Get the order object from the Order ID
    $order = wc_get_order( $order_id ); 
}

if( isset( $order ) && is_object( $order ) ){
    $count = 0;
    // Loop through order items
    foreach( $order->get_items() as $item ){
        // add item quantities to the count
        $count += (int) $item->get_quantity();
    }
    // Output the total items count
    echo $count;
}

这次应该更好用了……