我需要檢查購物車以查看是否在任何產品上添加了特定的產品屬性。 (這是在掛鉤到 woocommerce_package_rates 的自訂運輸功能內。)
我有購物車中每個商品的變體 ID,但我不知道如何取得該商品的變體 slug...
foreach (WC()->cart->get_cart() as $cart_item) { // $product_in_cart = $cart_item['product_id']; $variation_id = $cart_item['variation_id'] > 0 ? $cart_item['variation_id'] : $cart_item['product_id']; $variation = wc_get_product($variation_id); $variation_name = $variation->get_formatted_name(); //I want to get the slug instead. // if there is the swatch variation of any product in the cart. if ( $variation_name == 'swatch') $cart_has_swatch = "true"; }
P粉6004020852024-02-05 09:13:39
你造成了一些混亂。在 WooCommerce 購物車專案:
$cart_item['data']
;$cart_item['variation']
存取變體屬性(這是產品屬性分類法、產品屬性 slug 值對的陣列)。 $variation->get_formatted_name()
是產品變體名稱(已格式化),因此不是變體產品屬性。 </li>
woocommerce_package_rates
過濾器掛鉤,使用$package['contents']
而不是WC()->cart->get_cart()
。 您的問題不是很清楚,因為我們不知道您是否在屬性分類法或屬性段值中搜尋術語「樣本」。
嘗試以下操作:
add_filter( 'woocommerce_package_rates', 'filtering_woocommerce_package_rates', 10, 2 ); function filtering_woocommerce_package_rates( $rates, $package ) { $cart_has_swatch = false; // initializing // Loop through cart items in this shipping package foreach( $package['contents'] as $cart_item ) { // Check for product variation attributes if( ! empty($cart_item['variation']) ) { // Loop through product attributes for this variation foreach( $cart_item['variation'] as $attr_tax => $attr_slug ) { // Check if the world 'swatch' is found if ( strpos($attr_tax, 'swatch') !== false || strpos( strtolower($attr_slug), 'swatch') !== false ) { $cart_has_swatch = true; // 'swatch' found break; // Stop the loop } } } } if ( $cart_has_swatch ) { // Do something } return $rates; }
它應該適合你。