我试图制作一些我可以放在我的functions.php中的代码 它需要检查购物车中第一个产品的选定属性。之后,它需要阻止所有其他产品使用OTHER属性而不是购物车中的选定属性。
在我的情况下: 产品1具有属性:颜色,属性:高度。 产品2具有属性:颜色,属性:高度。 等。
如果 产品1加入购物车中,颜色为黑色。 然后 商店里的所有其他产品只能添加黑色。
我有几个尝试编辑现有代码,但没有一个工作:S
function check_if_cart_has_product( $valid, $product_id, $quantity ) {
if(!empty(WC()->cart->get_cart()) && $valid){
foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
if( $product_id == $_product->id ) {
wc_add_notice( 'The product is already in cart', 'error' );
return false;
}
}
}
return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'check_if_cart_has_product', 10, 3 );
这样只会在购物车中生产一件产品并阻止其他产品,只需检查正确的条件......
我尝试将它与这些代码组合起来但没有成功
function get_variation_data_from_variation_id( $item_id ) {
$_product = new WC_Product_Variation( $item_id );
$variation_data = $_product->get_variation_attributes();
$variation_detail = woocommerce_get_formatted_variation( $variation_data, true ); // this will give all variation detail in one line
// $variation_detail = woocommerce_get_formatted_variation( $variation_data, false); // this will give all variation detail one by one
return $variation_detail; // $variation_detail will return string containing variation detail which can be used to print on website
// return $variation_data; // $variation_data will return only the data which can be used to store variation data
}