简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM