Search code examples
phpwordpresswoocommercecheckoutcategories

WooCommerce Checkout url hook - Change condition based on product category


Wondering if anyone could help me to customize this code. I would like to change the applied condition in this code:

add_filter( 'woocommerce_get_checkout_url', 'change_checkout_url', 30 );
function change_checkout_url( $url ) {
    $allowed_countries = array('NO');
    $customer_country = WC()->customer->get_default_country();
    if( !in_array( $customer_country , $allowed_countries ) ) {
        $url = wc_get_page_permalink( 'checkout' );
    }
    return $url;
}

Is it possible instead, for products that belongs to some category in WooCommerce, to have a custom checkout url?


Solution

  • 2020 Update: Only for WooCommerce 3+

    Yes it's possible, making some changes:

    add_filter( 'woocommerce_get_checkout_url', 'custom_checkout_url', 30 );
    function custom_checkout_url( $checkout_url ) {
    
        // Define your product categories (term Id, slug or name)
        $categories = array('Cat name1', 'Cat name2'); 
        $custom_url = 'http://my_custom_url.com/checkout/'; // <= custom URL
    
        $cart_items = WC()->cart->get_cart();
    
        if ( sizeof($cart_items) > 0 ) {
            foreach ( $cart_items as $cart_item ) {
                if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ){
                     return $custom_url;
                }
            }
        }
        return $checkout_url;
    }
    

    This code goes in your plugin file or on function.php file of your active child theme or theme

    References: