php 在Woocommerce中获取订单标题

0wi1tuuw  于 2023-02-03  发布在  PHP
关注(0)|答案(4)|浏览(165)

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

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

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

然后我这样称呼标题:

$_product->post_title

这个很有效,它会返回我订购的产品的名称。问题是当我有2个或更多的产品时,它仍然会返回我1个名称。我如何使它返回购物车中的所有名称。

5sxhfpxr

5sxhfpxr1#

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
x0fgdtte

x0fgdtte2#

<?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
?>
hrirmatl

hrirmatl3#

尝试此代码,它返回购物车中的所有名称。

global $woocommerce; 

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

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

exit();
ki1q1bka

ki1q1bka4#

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

$产品名称=内爆(“\n”,$产品发布标题在购物车中);
这是一个非常好的例子.

相关问题