在 WooCommerce 中,我想检查购物车中的产品是否具有属性 'Varifocal'
(以便我可以显示/隐藏结帐字段)。
我正在努力获取具有“变焦”属性的所有变体的 ID 数组。如果有人能指出我正确的方向,我将不胜感激。
分类法是 pa_lenses
。
我目前有以下功能:
function varifocal() {
// Add product IDs here
$ids = array();
// Products currently in the cart
$cart_ids = array();
// Find each product in the cart and add it to the $cart_ids array
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
$cart_product = $values['data'];
$cart_ids[] = $cart_product->get_id();
}
// If one of the special products are in the cart, return true.
if ( ! empty( array_intersect( $ids, $cart_ids ) ) ) {
return true;
} else {
return false;
}
}
最佳答案
这是一个自定义条件函数,当在一个购物车项目中找到特定属性参数时,它将返回 true
(产品变体) :
function is_attr_in_cart( $attribute_slug_term ){
$found = false; // Initializing
if( WC()->cart->is_empty() )
return $found; // Exit
else {
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ){
if( $cart_item['variation_id'] > 0 ){
// Loop through product attributes values set for the variation
foreach( $cart_item['variation'] as $term_slug ){
// comparing attribute term value with current attribute value
if ( $term_slug === $attribute_slug_term ) {
$found = true;
break; // Stop current loop
}
}
}
if ($found) break; // Stop the first loop
}
return $found;
}
}
代码进入事件子主题(或事件主题)的 functions.php 文件。经过测试并有效。
USAGE (example)
if( is_attr_in_cart( 'Varifocal' ) ){
echo '"Varifocal" attribute value has been found in cart items<br>';
} else {
echo '"Varifocal" <strong>NOT FOUND!!!</strong><br>';
}
Advice: This conditional function will return false if cart is empty
关于php - 检查购物车项目(产品变体)中是否使用了特定的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41304266/