Last active
November 15, 2023 12:18
-
-
Save createit-dev/5b2c6c45bc1598c778675c9b6265069a to your computer and use it in GitHub Desktop.
Calculating WooCommerce Shipping Costs - WooCode Tips Series
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Calculate Shipping Costs Programmatically in WooCommerce | |
* - fetch standard methods | |
* - integrate with Flexible-shipping Plugin | |
*/ | |
function ct_get_available_shipping_methods_for_customer_cart($country_code = 'PL') { | |
if (function_exists('WC')) { | |
if (!WC()->cart || WC()->cart->is_empty()) { | |
return array(); | |
} | |
$enabled_methods = array(); | |
$package = WC()->cart->get_shipping_packages()[0]; // Assuming single package | |
$package['destination'] = array('country' => $country_code); | |
$zones = WC_Shipping_Zones::get_zones(); | |
foreach ($zones as $zone) { | |
$matching_locations = array_filter($zone['zone_locations'], function ($location) use ($country_code) { | |
return $location->code == $country_code; | |
}); | |
if (!empty($matching_locations)) { | |
$shipping_zone = new WC_Shipping_Zone($zone['id']); | |
$available_methods = $shipping_zone->get_shipping_methods(true); | |
foreach ( $available_methods as $method ) { | |
if ( $method->is_enabled() ) { | |
// Set the current package | |
if ( method_exists( $method, 'calculate_shipping' ) ) { | |
$method->calculate_shipping( $package ); | |
$rates = $method->rates; | |
foreach ( $rates as $rate ) { | |
$enabled_methods[] = array( | |
'method_title' => $method->get_method_title(), | |
'method_id' => $rate->get_id(), | |
'cost' => floatval($rate->get_cost()), | |
); | |
} | |
} | |
else { | |
$method_id = get_class($method); | |
$enabled_methods[] = array( | |
'method_title' => $method->get_method_title(), | |
'method_id' => $method_id, | |
'cost' => floatval($method->get_option('cost')), | |
); | |
} | |
} | |
} | |
return $enabled_methods; | |
} | |
} | |
} else { | |
return array(); | |
} | |
} | |
add_action('wp_loaded', 'ct_test_script_1'); | |
function ct_test_script_1() { | |
$param_name = 'ct_trigger_shipping_methods_info'; | |
// Check if the special query string parameter is present | |
if (isset($_GET[$param_name]) && !empty($_GET[$param_name])) { | |
$shipping_methods = ct_get_available_shipping_methods_for_customer_cart(); | |
header('Content-Type: application/json'); | |
echo json_encode($shipping_methods); | |
exit; // Stop further execution to prevent loading the full page | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment