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

时间:2018-05-09 11:34:09

标签: php wordpress methods woocommerce cart

我修改了email-order-details.php代码,以便能够包含项目总数。

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

除了一个案例外,这种方法很有效。

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

致命错误:在第61行的email-order-details.php中调用null上的成员函数get_cart_contents_count()

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

谢谢!

暂时解决:

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

1 个答案:

答案 0 :(得分:2)

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

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

它也应该有用。

现在,对于电子邮件,可能是您定位“订购商品”而不是。如果是这种情况,您将需要获取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;
}

这次应该会更好......