How to restrict cart value based on url in woocommerce

Question

I’m trying to add some condition in the product cart quantities based on the URL in woocommerce

Like if the URL has a certain string than restrict cart value

// Checking and validating when products are added to cart
global $wp;
$url = home_url(add_query_arg(array(), $wp->request));

$isurlhas = strpos($url, 'four');
if ($isurlhas!==false)
{

add_filter( 'woocommerce_add_to_cart_validation', 'only_six_items_allowed_add_to_cart', 30, 3 );

function only_six_items_allowed_add_to_cart( $passed, $product_id, $quantity ) {

    $cart_items_count = WC()->cart->get_cart_contents_count();
    $total_count = $cart_items_count + $quantity;

    if( $cart_items_count >= 4 || $total_count > 4 ){
        // Set to false
        $passed = false;
        // Display a message
         wc_add_notice( __( "You can’t have more than 4 items in cart", "woocommerce" ), "error" );
    }
    return $passed;
}
} else{
    add_filter( 'woocommerce_add_to_cart_validation', 'only_six_items_allowed_add_to_cartt', 30, 3 );

function only_six_items_allowed_add_to_cartt( $passed, $product_id, $quantity ) {

    $cart_items_count = WC()->cart->get_cart_contents_count();
    $total_count = $cart_items_count + $quantity;

    if( $cart_items_count >= 2 || $total_count > 2 ){
        // Set to false
        $passed = false;
        // Display a message
         wc_add_notice( __( "You can’t have more than 2 items in cart", "woocommerce" ), "error" );
    }
    return $passed;
}
    
}

I add this code in the snippet but it not working

I want if the URL has a word shop/?quantity=4 then cart value never more than 4 & if shop/?quantity=2 then cart value 2

also i try

if (strpos($_SERVER['REQUEST_URI'], "4") !== false ){
add_filter( 'woocommerce_add_to_cart_validation', 'only_four_items_allowed_add_to_cart', 30, 3 );

function only_four_items_allowed_add_to_cart( $passed, $product_id, $quantity ) {

    

$cart_items_count = WC()->cart->get_cart_contents_count();
$total_count = $cart_items_count + $quantity;

if( $cart_items_count >= 4 || $total_count > 4 ){
    // Set to false
    $passed = false;
    // Display a message
     wc_add_notice( __( "You can’t have more than 4 items in cart", "woocommerce" ), "error" );
}
return $passed;

}
} else{
add_filter( ‘woocommerce_add_to_cart_validation’, ‘only_two_items_allowed_add_to_cartt’, 40, 3 );

function only_two_items_allowed_add_to_cart( $passed, $product_id, $quantity ) {

$cart_items_count = WC()->cart->get_cart_contents_count();
$total_count = $cart_items_count + $quantity;

if( $cart_items_count >= 2 || $total_count > 2 ){
    // Set to false
    $passed = false;
    // Display a message
     wc_add_notice( __( "You can’t have more than 2 items in cart", "woocommerce" ), "error" );
}
return $passed;

}

}

0
Tarun Rajpurohit 4 months 0 Answers 11 views 0

Leave an answer