Wordpress Woocommerce get_cart in theme function.php获取错误消息“get_cart()on null”

Wordpress Woocommerce get_cart in theme function.php获取错误消息“get_cart()on null”,wordpress,woocommerce,Wordpress,Woocommerce,下面是我用来从购物车获取产品的代码 global $woocommerce; $items = WC()->cart->get_cart(); 我在主题文件夹的functions.php中有这段代码 问题是每次我运行这段代码时,都会收到错误消息说 致命错误:在null上调用成员函数get_cart 我错过了什么?你可以这样使用 global $woocommerce; $items = $woocommerce->cart->get_cart(); foreach($i

下面是我用来从购物车获取产品的代码

global $woocommerce;
$items = WC()->cart->get_cart();
我在主题文件夹的functions.php中有这段代码

问题是每次我运行这段代码时,都会收到错误消息说

致命错误:在null上调用成员函数get_cart

我错过了什么?

你可以这样使用

global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) 
{ 
    $_product =  wc_get_product( $values['data']->get_id()); 
    echo "<b>".$_product->get_title().'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
    $price = get_post_meta($values['product_id'] , '_price', true);
    echo "  Price: ".$price."<br>";
} 

您的代码是有效的,但是您可能是从后端或没有购物车的地方调用它。您可能希望处理订单中的订单项目

// Get an instance of the WC_Order object
$order = wc_get_order($order_id);

// Iterating through each WC_Order_Item_Product objects
foreach ($order->get_items() as $item_key => $item_values):

## Using WC_Order_Item methods ##

// Item ID is directly accessible from the $item_key in the foreach loop or
$item_id = $item_values->get_id();

## Using WC_Order_Item_Product methods ##

$item_name = $item_values->get_name(); // Name of the product
$item_type = $item_values->get_type(); // Type of the order item ("line_item")

endforeach;

此代码只需在前端模板或挂钩函数上使用,因为cart是与当前客户相关的活动对象……因此您应该在使用此代码的位置添加完整代码并提供更多详细信息。注:WC取代旧的全球商务;