Skip to content

Instantly share code, notes, and snippets.

@opicron
Last active October 20, 2022 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save opicron/b90e2f3d29552ca8f8f2f4364f7a582e to your computer and use it in GitHub Desktop.
Save opicron/b90e2f3d29552ca8f8f2f4364f7a582e to your computer and use it in GitHub Desktop.
Add dropshipment costs #php #woocommerce
<?php
add_filter( 'woocommerce_package_rates', 'custom_shipping_costs', 20, 2 );
function custom_shipping_costs( $rates, $package )
{
// New shipping cost (can be calculated)
$new_cost = 5;
$tax_rate = 0.21;
global $woocommerce;
//$address = ( !empty( $woocommerce->customer->get_shipping_address_1() ) ) ? $woocommerce->customer->get_shipping_address_1() : $woocommerce->customer->get_billing_address_1();
//$postcode = ( !empty( $woocommerce->customer->get_shipping_postcode() ) ) ? $woocommerce->customer->get_shipping_postcode() : $woocommerce->customer->get_billing_postcode();
foreach( $rates as $rate_key => $rate )
{
// Excluding free shipping methods
if( $rate->method_id == 'free_shipping')
{
if ( WC()->customer->get_shipping_address_1() != WC()->customer->get_billing_address_1() )
{
//works but doesnt remove the free shipping cost from checkout
//WC()->cart->add_fee( 'Dropshipment ', $new_cost, true );
//instead we use this but it is not working 100% (for visibility)
$rates[$rate_key]->method_id = 'flat_rate';
$rates[$rate_key]->label = __( 'Dropshipment', 'woocommerce' ); // New label name
$rates[$rate_key]->cost = $new_cost; // * (1 + $tax_rate);
// working, but not showing on VAT line in checkout..
// Set taxes rate cost (if enabled)
if( ! WC()->customer->is_vat_exempt() )
{
$taxes = array();
$taxes['sub_total'] = $new_cost * $tax_rate;
$rates[$rate_key]->taxes = $taxes;
}
/*
// example from online but doesnt calculate VAT because taxes keys are not set..
// Set taxes rate cost (if enabled)
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $rates[$rate_key]->taxes[$key] > 0 )
$taxes[$key] = $new_cost * $tax_rate;
}
*/
}
}
}
return $rates;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment