【问题标题】:Get order title(s) in Woocommerce在 Woocommerce 中获取订单标题
【发布时间】:2016-12-08 10:11:38
【问题描述】:

我正在尝试通过我的functions.php 文件循环获取订购产品的名称。这是我的代码:

global $woocommerce;
$items = $woocommerce->cart->get_cart();

foreach($items as $item => $values) { 
    $_product = $values['data']->post; 
} 

然后我这样称呼标题:

$_product->post_title

这可行,它会返回我订购的产品的名称。问题是当我有 2 个或更多产品时,它仍然返回我 1 个名称。我怎样才能使它返回购物车中的所有名称。

【问题讨论】:

  • 您是否正在检查 foreach 循环中的标题?您的示例中并不清楚。
  • 现在你想做什么??
  • 我认为这已经解决了

标签: php wordpress woocommerce cart product


【解决方案1】:

woocommerce 中相对于购物车的新语法是使用 WC() 制作的,无需调用 global woocommerce;

所以你的代码是这样的:

$products_in_cart= array();
$products_post_title_in_cart = array();
$products_ids_in_cart= array();

foreach(WC()->cart->get_cart() as $cart_item) {
    $products_in_cart[] = $cart_item['data']->post;
    $products_post_title_in_cart[] = $cart_item['data']->post->post_title;
    $products_ids_in_cart[] = $cart_item['product_id'];
}

// The first product (or item of the cart)
$_product = $products_in_cart[0]; // product post data
$product_id = $products_ids_in_cart[0]; // product ID
$products_post_title_in_cart[0] // product post title

// The Second product (or item of the cart)
$_product = $products_in_cart[1]; // product post data
$product_id = $products_ids_in_cart[1]; // product ID
$products_post_title_in_cart[1] // product post title

// etc … for all other products you increase the key of the arrays to get the correct values

【讨论】:

  • 感谢您的回答。我是中级。
  • @VasimVanzara 反正我也不回答你了……这和等级无关……每个人都可以不考虑等级就回答吗?
  • 当我将 2 个产品添加到购物车时,它只返回 1 个产品
  • @Kevin.a 这很正常,因为您需要其他产品来购买第二个产品……我更新了我的答案
  • @Kevin.a 更新了我的答案……因为它是一个 foreach 循环,它遍历购物车中的每个项目……如果您有 10 个项目,则必须增加数组的键值才能获得正确的数据。这个键值是0 用于第一项,1 用于第二项,依此类推……
【解决方案2】:
<?php
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();
    $arr_product=array();
        foreach($items as $item => $values) {             
           $arr_product[]= $_product->post_title;            
        } 
    print_r($arr_product,true); // echo print_r(); thats why get 1
?>

【讨论】:

  • 您好,感谢您的回复。但我需要调用 $_product['my_post']->post_title;在 for 循环之外
  • 如果我添加 2 它仍然返回 1 项目名称它返回 1
  • 全球 $woocommerce; $items = $woocommerce->cart->get_cart(); print_r($items);退出;
  • 您可以将该数组粘贴到您的问题中
  • 它返回一个数字,数字是1
【解决方案3】:

试试这个代码,它会返回购物车中的所有名字。

global $woocommerce; 

$cart_item = $woocommerce->cart->get_cart(); 

echo "<pre>";
print_r($cart_item);

exit();

【讨论】:

    猜你喜欢
    • 2021-12-06
    • 2018-03-16
    • 2019-09-08
    • 2018-05-26
    • 2014-03-05
    • 2022-01-14
    • 2018-10-26
    • 1970-01-01
    相关资源
    最近更新 更多