亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 WooCommerce 中的購物車項目中獲取產品類別術語

從 WooCommerce 中的購物車項目中獲取產品類別術語

PHP
精慕HU 2021-12-24 15:37:18
我只得到一些產品的產品類別,一些我沒有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 回答

?
飲歌長嘯

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>";

    }

}


查看完整回答
反對 回復 2021-12-24
  • 1 回答
  • 0 關注
  • 122 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號