Php 商业产品属性限制

Php 商业产品属性限制,php,wordpress,woocommerce,Php,Wordpress,Woocommerce,我有一个想法,就是尝试制作一张可以放入functions.php中的代码图片 它需要检查购物车中第一个产品的选定属性。之后,它需要阻止所有其他产品与其他属性,而不是在购物车中选择的一个 就我而言: 产品1具有属性:颜色,属性:高度。 产品2具有属性:颜色,属性:高度。 等等 如果 产品1以黑色添加到购物车中。 然后 店内所有其他产品只能添加黑色 我尝试过几次编辑现有代码,但都不管用:s function check_if_cart_has_product( $valid, $produc

我有一个想法,就是尝试制作一张可以放入functions.php中的代码图片 它需要检查购物车中第一个产品的选定属性。之后,它需要阻止所有其他产品与其他属性,而不是在购物车中选择的一个

就我而言: 产品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
}