KPL
KPL

Reputation: 31

Woocommerce Redirecting Add to Cart button conditionally

After adding a certain product to the cart I would like the user to be redirected to a different page. I have tried several snippets from around the web, but all of my conditional logic returns null or 0 when I enter it in functions.php. I have tried conditions based on the page, the product, and the category. This is the latest snippet I found from another answer on here and it's not working for me, any idea why?

    add_filter ('add_to_cart_redirect', 'redirect_to_checkout');
    function redirect_to_checkout() {
            global $woocommerce;
            //Get product ID
            $product_id = (int) apply_filters('woocommerce_add_to_cart_product_id', $_POST['product_id']);
            //Check if product ID is in a certain taxonomy
            if( has_term( 'sidestix', 'product_cat', $product_id ) ){
                        //Get cart URL
                        $checkout_url = get_permalink(get_option('woocommerce_checkout_page_id'));
                        //Return the new URL
                        return $checkout_url;
             }
    }

Upvotes: 2

Views: 2029

Answers (1)

KPL
KPL

Reputation: 31

I finally found a working snippet on a different forum. I can see the difference, but I'm not sure why it works.

    add_filter ('add_to_cart_redirect', 'redirect_to_checkout');
    function redirect_to_checkout() {
            global $woocommerce;

            //Get product ID
            $product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint($_REQUEST['add-to-cart'] ) );
            //Check if product ID is in a certain taxonomy
            if( has_term( 'Philanthropy', 'product_cat', $product_id ) ){
                        //Get cart URL
                        $checkout_url = get_permalink(get_option('woocommerce_checkout_page_id'));
                        //Return the new URL
                    return $checkout_url;
             };
    }

Upvotes: 1

Related Questions