Syed Reza Ali Syed Reza Ali - 3 months ago 30
PHP Question

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:

<?php
/*
Plugin Name: Modify Klarna Checkout URL
Plugin URI: http://krokedil.com
Description: Change checkout URL for Klarna Checkout if user isn't from a specific country
Version: 1.0
Author: Krokedil
Author URI: http://krokedil.com
*/
add_filter( 'woocommerce_get_checkout_url', 'krokedil_change_checkout_url', 30 );
function krokedil_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?

Thanks

Answer

Yes it's possible, making some changes:

add_filter( 'woocommerce_get_checkout_url', 'krokedil_change_checkout_url', 30 );
function krokedil_change_checkout_url( $checkout_url ) {

    // Define your SPECIAL CATEGORY here AND your CUSTOM URL
    $my_cat = 'Cat name'; // or for multiple categories
    // $my_cat = array('Cat name1', 'Cat name2'); 
    $my_url = 'http://my_custom_url.com/checkout/'; // custom URL

    $bool_cat = false;
    if ( sizeof( WC()->cart->cart_contents) > 0 ) {
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            $item = $cart_item['data'];

            // =>  Updated a mistake in this line
            if(!empty($item) && !$bool_cat && has_term( $my_cat, 'product_cat', $item->id ) ){
                $bool_cat = true;
            }
        }
        if ( $bool_cat ) { 
            $checkout_url = $my_url;
        } 
        // This is optional
        else {
            $checkout_url = WC()->cart->get_checkout_url();
        }
    }
    return $checkout_url;
}

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

References:

Comments