我需要检查购物车以查看是否在任何产品上添加了特定的产品属性。 (这是在挂钩到 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 ( $variation_name == 'swatch') $cart_has_swatch = "true"; // if there is the swatch variation of any product in the cart.
}
你正在制造混乱。在 WooCommerce 购物车商品上:
$cart_item['data']
;$cart_item['variation']
(产品属性分类法、产品属性 slug 值对的数组)访问变体属性。$variation->get_formatted_name()
是产品变体名称(已格式化)您的问题不是很清楚,因为我们不知道您是在属性分类中还是在属性段值中搜索术语“样本”。
尝试以下操作:
$cart_has_swatch = false; // initializing
// Loop through cart items
foreach (WC()->cart->get_cart() as $cart_item) {
// Check for product variations
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($attr_slug, 'swatch') !== false ) {
$cart_has_swatch = true; // 'swatch' found
break; // Stop the loop
}
}
}
}
if ( $cart_has_swatch ) {
// Do something
}
它应该适合你。