0
votes

I wish to make multiple specific subscription products skip the cart and go straight to checkout. I found the following code here (only for one product), which skips it for one product using the product ID, but unable to adapt it for multiple products. Tried also various other methods, but none seem to work for Woocommerce 4.51

How to skip cart page on woocomerce for certain products only?

add_filter( 'woocommerce_add_to_cart_redirect', 'woo_redirect_checkout' );

function woo_redirect_checkout() {

   global $woocommerce;

   $desire_product = '73458';

   //Get product ID

   $product_id = (int) apply_filters( 'woocommerce_add_to_cart_product_id', $_POST['add-to-cart'] );

   //Check if current product is subscription

   if ( $product_id == $desire_product ){

       $checkout_url = $woocommerce->cart->get_checkout_url();

       return $checkout_url;

       exit;

   } else {

       $cart_url = $woocommerce->cart->get_cart_url();

       return $cart_url;

       exit;

   }

}
1

1 Answers

2
votes

The woocommerce_add_to_cart_redirect filter gives you access to the product object of the product that was added to the cart. So you can check for the subscription product type:

add_filter( 'woocommerce_add_to_cart_redirect', 'woo_redirect_checkout', 10, 2 );
function woo_redirect_checkout( $url, $product ) {
    return $product->get_type() == 'subscription' ? wc_get_checkout_url() : $url;
}

Now all products that are of type subscription get redirected to the checkout instead of the cart.

If you do not want all your subscription products to redirect to the checkout but only subscriptions in certain categories, you can first retrieve the product categories from the product object and see if they match one of the categories defined in the $checkout_cats array:

add_filter( 'woocommerce_add_to_cart_redirect', 'woo_redirect_checkout', 10, 2 );
function woo_redirect_checkout( $url, $product ) {

    //Define your categories here
    $checkout_cats = array( 'Music', 'Posters' );

    if ( $product->get_type() == 'subscription' ) {
        $terms = get_the_terms( $product->get_id(), 'product_cat' );
        if ( !empty( $terms ) ) {
            foreach ( $terms as $term ) {
                if ( in_array( $term->name, $checkout_cats ) ) return wc_get_checkout_url();
            }
        }
    }

    return $url;
}