[英]Get the product categories and display it on cart page woocommerce
I am trying to display the categories of each product on a cart page. 我正在尝试在购物车页面上显示每种产品的类别。 I have not much knowledge of php. 我对php的了解不多。 I am using this code: 我正在使用此代码:
$terms = get_the_terms( $product_id, 'product_cat' );
foreach ($terms as $term) {
$product_cat = $term->name;
}
echo $product_cat ;
To test this code I put in one <div>
in the woocommerce/cart/cart.php
just under the foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item )
loop and it worked, but it shows me only the last category of each products, not all categories. 为了测试这个代码,我把一个<div>
在woocommerce/cart/cart.php
刚下foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item )
循环和它的工作,但它仅显示每个产品的最后一个类别,而不显示所有类别。
I would like to show all the categories, and not in the beginning of the page but just after the shipping info before the sub-total and the total. 我想显示所有类别,而不是在页面的开头,而是在运送信息之后,小计和总计之前。
I tried to put this code in the cart-totals.php
in a new <tr><th>Some Title</th><td>[PHP Code here]</td></tr>
but it showed nothing as a result. 我试图将这段代码放在新的<tr><th>Some Title</th><td>[PHP Code here]</td></tr>
中的cart-totals.php
中,但没有显示任何内容结果。 I thinks that its because the code goes out from the foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item )
. 我认为这是因为代码从foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item )
消失了foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item )
。 Any help would be appreciated, thanks 任何帮助,将不胜感激,谢谢
[EDIT] [编辑]
I don't know if this is the best way to do it but this code seems to work in the cart-total.php
我不知道这是否是最好的方法,但是此代码似乎可以在cart-total.php
<?php
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
$product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
$terms = get_the_terms( $product_id, 'product_cat' );
$product_cat = array();
foreach ($terms as $term) {
$product_cat[] .= $term->name;
}
echo implode(', ', $product_cat);
?>
Thanks :) 谢谢 :)
Try with 试试看
$terms = get_the_terms( $product_id, 'product_cat' );
$product_cat = array();
foreach ($terms as $term) {
$product_cat[] .= $term->name;
}
echo implode(', ', $product_cat);
This will put all your categories in an array, and you can implode it to output it as a string separated by a comma. 这会将所有类别放置在一个数组中,您可以将其内爆以字符串形式输出,并用逗号分隔。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.