Skip to content

Instantly share code, notes, and snippets.

@cklosowski
Created August 5, 2015 06:09
Show Gist options
  • Save cklosowski/97dd2558879719f11c20 to your computer and use it in GitHub Desktop.
Save cklosowski/97dd2558879719f11c20 to your computer and use it in GitHub Desktop.
Add fees to the WooCommerce cart, based on the state chosen for shipping
<?php
/**
* Plugin Name: WooCommerce - Fees by State
* Plugin URI: https://filament-studios.com/
* Description: Add Fees to the cart based off the shipping state
* Version: 1.0
* Author: Filament Studios
* Author URI: https://filament-studios.com
* License: GPL-2.0+
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
function fs_per_state_fees() {
global $woocommerce;
$packages = $woocommerce->shipping->packages;
$state_fees = array(
'CA' => array( // Start of CA fees
'amount' => 2,
'is_taxable' => false,
'name' => __( 'CA Fee', 'woo-psf' ),
), // End of CA Fees
'AZ' => array( // Start of AZ fees
'amount' => 3.25,
'is_taxable' => true,
'name' => __( 'AZ Fee', 'woo-psf' ),
), // End of AZ fees
);
foreach ( $packages as $package ) {
$state = ! empty( $package['destination']['state'] ) ? strtoupper( $package['destination']['state'] ) : false;
if ( ! empty( $state ) && array_key_exists( $state, $state_fees ) ) {
$fee = $state_fees[ $state ]['amount'];
$is_taxable = $state_fees[ $state ]['is_taxable'];
$name = $state_fees[ $state ]['name'];
if ( ! empty( $fee ) ) {
$woocommerce->cart->add_fee( $name, $fee, $is_taxable, '' );
}
}
}
}
add_action( 'woocommerce_cart_calculate_fees', 'fs_per_state_fees' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment