Last active
July 26, 2016 05:16
-
-
Save blakewilson/1d1be3ed68526dc12a5cb28d44cb6316 to your computer and use it in GitHub Desktop.
Add a fixed surcharge to your cart and checkout based on array of product IDs in cart –– WooCommerce
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 | |
/** | |
* Add a fixed surcharge to your cart and checkout based on array of | |
* product ids in cart. | |
* | |
* @author Blake Wilson | |
* @link https://gist.github.com/blakewilson/1d1be3ed68526dc12a5cb28d44cb6316 | |
* @license MIT | |
* @license https://opensource.org/licenses/MIT | |
* | |
* @var array $products_array Should be an array of WooCommerce product IDs | |
* @var integer $fixed_fee The fee amount as an integer | |
* @var string $surcharge_name The name of the surcharge, localized for WordPress | |
*/ | |
function themeprefix_woocommerce_surcharge() { | |
global $woocommerce; | |
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) | |
return; | |
/** | |
* Setup the array of products that have a surcharge | |
*/ | |
$products_array = array( '99', '572' ); | |
/** | |
* Our fee amount | |
*/ | |
$fixed_fee = 2.00; | |
/** | |
* The surcharge name | |
*/ | |
$surcharge_name = __( 'Surcharge', 'text-domain' ); | |
/** | |
* Loop through the cart looking for products that match the ids of the | |
* $products_array array | |
*/ | |
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) { | |
if ( in_array( $values['product_id'], $products_array ) ) { | |
$woocommerce->cart->add_fee( $surcharge_name, $fixed_fee, true, '' ); | |
} | |
} | |
} | |
add_action( 'woocommerce_cart_calculate_fees', 'themeprefix_woocommerce_surcharge' ); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment