1 回答

TA貢獻1951條經驗 獲得超3個贊
首先你的$product_cat變量沒有定義。
要獲取購物車項目上的產品類別,您需要獲取產品變體的父變量產品 ID,因為它們不會將自定義分類法作為產品類別或產品標簽進行處理。
要為購物車項目上的任何自定義分類術語獲取正確的產品 ID,請始終使用:
$product_id = $cart_item['product_id'];
代替:
$product_id = $cart_item['data']->get_id();
現在,如果您需要獲取產品類別術語名稱,而不是使用get_the_terms()函數,您可以使用wp_get_post_terms()和implode()函數,例如:
$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>';
所以在購物車項目 foreach 循環中:
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$quantity = $cart_item['quantity'];
$product_id = $cart_item['product_id'];
$variation_id = $cart_item['variation_id'];
echo __("PRODUCT ID: ") . $product_id . "<br>";
$term_names = wp_get_post_terms( $product_id, 'product_cat', array('fields' => 'names') );
if ( count($term_names) > 0 ) {
echo __("PRODUCT CATEGORY: ") . implode("<br>", $term_names) . "<br>";
}
}
- 1 回答
- 0 關注
- 122 瀏覽
添加回答
舉報