Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce Add to Cart Condition

I recently implement the code in function.php to redirect url when the price is 0 but it seems its only lacking and the price condition is not working. See my codes.

/**
 * Set a custom add to cart URL to redirect to
 * @return string
 **/

function custom_add_to_cart_redirect() { 
      $_product = wc_get_product( $product_id );
      if( $product->get_price() == 0 ||  $product->get_price() == '') {
        return 'http://www.nichegas.ads-tracker.com/contact/'; 
        }
}
add_filter( 'woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect' );

It seems I am lacking on some code or something. Our objective are: 1. IF price is 0 it will redirect to out custom url 2 also when click the add to card and its zero its will not add the item to the cart. How to disable the addition of product?

Your help will very much appreciated. Have a nice day!

like image 401
Abs Duls Avatar asked Jan 25 '26 17:01

Abs Duls


1 Answers

UPDATE

Alternatively you can use also woocommerce_add_to_cart hook instead, and **here is possible to remove the freshly added item, this way:

add_action( 'woocommerce_add_to_cart', 'custom_add_to_cart', 10, 2 );
function custom_add_to_cart( $cart_item_key, $product_id ) {

    $_product = wc_get_product($product_id);
    $_product_price = $_product->get_price();
    if( $_product_price == 0 || empty($_product_price) ) {

        // Removing this freshly added cart item
        WC()->cart->remove_cart_item($cart_item_key);

        // Redirecting to some url
        wp_redirect( 'http://www.nichegas.ads-tracker.com/contact/' );

        exit; 
    }
}

Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.

like image 131
LoicTheAztec Avatar answered Jan 28 '26 08:01

LoicTheAztec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!