在 Woocommerce 购物车和结帐中显示项目产品类别名称

Display item product categories names in Woocommerce cart and checkout

我正在使用 Woocommerce 3.3.3。和可视化产品配置器 4.0

My web site 中,您可以将一些产品添加到购物车并继续结帐

  1. 我有 edited cart/cart.php 模板在购物车中显示我的产品类别名称 (从第 75 行到第 79 行)。

代码

<?php
        do_action( 'woocommerce_review_order_before_cart_contents' );

        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 );
            $terms = get_the_terms( $product_id, 'product_cat' );
            foreach ($terms as $term) {
            $product_cat = $term->name;
            }
            echo $product_cat ;

那个位置可以吗?

  1. edited checkout/review-order.php 在结帐时显示我的类别名称(从第 36 行到第 41 行):

        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' );
            foreach ($terms as $term) {
            $product_cat = $term->name;
            }
            echo $product_cat ;
    

    我的类别名称显示了两次。我该如何解决?

之后我可以在结帐下看到我的类别名称但是它显示了两次

如何避免这种显示重复?
摆放位置好吗?

To display product categories inline linked names use wc_get_product_category_list().

第 1 点:

您应该用以下专用函数替换您的代码(更紧凑):

echo wc_get_product_category_list( $cart_item['product_id'] );

对于第 2 点:

您应该用以下代码替换您的代码以避免重复和错误格式 html (在模板 checkout/review-order.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 );
    ?>
        <tr class="product-categories">
            <td colspan="2"><?php echo wc_get_product_category_list( $cart_item['product_id'] ); ?></td>
        </tr>
    <?php

不要忘记在 html table…

中添加输出