对 null 调用成员函数 get_cart_contents_count()

jpu*_*acq 2 php methods wordpress cart woocommerce

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

echo WC()->cart->get_cart_contents_count();
Run Code Online (Sandbox Code Playgroud)

除了一种情况外,这种方法效果很好。

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

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

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

谢谢你!

暂时解决了:

if ( is_null(WC()->cart) ) {} else { echo WC()->cart->get_cart_contents_count(); }
Run Code Online (Sandbox Code Playgroud)

Loi*_*tec 6

您也可以使用这一行(就像WC()->cart实时WC_Cart实例对象一样)

\n\n
echo is_object( WC()->cart ) ? WC()->cart->get_cart_contents_count() : \'\';\n
Run Code Online (Sandbox Code Playgroud)\n\n

它也应该有效。

\n\n
\n\n

现在对于电子邮件,可能您的目标是“订购商品”。如果是这种情况,您将需要获得WC_Order对象\xe2\x80\xa6 如果没有,您可以从订单 ID\xe2\x80\xa6 获取它

\n\n
// If the WC_Order object doesn\'t exist but you have the Order ID\nif( ! ( isset( $order ) && is_object( $order ) ) && isset( $order_id ) ){\n    // Get the order object from the Order ID\n    $order = wc_get_order( $order_id ); \n}\n\nif( isset( $order ) && is_object( $order ) ){\n    $count = 0;\n    // Loop through order items\n    foreach( $order->get_items() as $item ){\n        // add item quantities to the count\n        $count += (int) $item->get_quantity();\n    }\n    // Output the total items count\n    echo $count;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这次应该可以更好地工作\xe2\x80\xa6

\n