从WooCommerce中的购物车项目中获取产品类别术语

时间:2019-09-03 16:27:40

标签: php wordpress woocommerce cart taxonomy-terms

我只在某些产品上获得产品类别,而在某些我没有的产品上

function savings_33_55_cart() {
    foreach ( WC()->cart->get_cart() as $key => $cart_item ) { 
        for ($i=0; $i < $cart_item['quantity'] ; $i++) {   
            $productId = $cart_item['data']->get_id();

            echo "PROD ID: " . $productId . "<br>";

            $terms = get_the_terms( $productId, 'product_cat' );

            foreach ($terms as $term) {
                $product_cat = $term->name;
                echo "PRODUCT CATEGORY: " . $product_cat . "<br>"; 
            }
        }
    }
}

add_action( 'woocommerce_cart_totals_before_order_total', 'savings_33_55_cart' );

我希望在每个产品上都有一个产品类别,但我只会在某些产品上获得该产品类别

1 个答案:

答案 0 :(得分:1)

首先,您的$product_cat变量未定义。

要在购物车商品上获取产品类别,您需要获取产品变体的父变量产品ID,因为它们不能将自定义分类法作为产品类别或产品标签来处理。

  

要始终使用购物车商品上的任何自定义分类条款获得正确的产品ID,请使用

$product_id = $cart_item['product_id']; 
     

代替:

$product_id = $cart_item['data']->get_id(); 


现在,如果您需要获取产品类别术语名称,则可以使用get_the_terms()wp_get_post_terms()函数,例如:< / p>

implode()


因此在购物车中的foreach循环中:

$term_names = wp_get_post_terms( $product_id, 'product_cat', ['fields' => 'names'] );

// Displaying term names in a coma separated string
if( count( $term_names ) > 0 )
    echo __("Product categories") . ": " . implode( ", ", $term_names ) . '<br>':

// OR displaying term names as a vertical list
if( count( $term_names ) > 0 )
    echo __("Product categories") . ": " . implode( "<br>", $term_names ) . '<br>';