Skip to content

Instantly share code, notes, and snippets.

@kloon
Created December 11, 2013 08:21
Show Gist options
  • Save kloon/7906768 to your computer and use it in GitHub Desktop.
Save kloon/7906768 to your computer and use it in GitHub Desktop.
WooCommerce apply a fee when certain products are in the cart
<?php
// Add a once-of fee to the cart when certain items are in the cart
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;
$apply_fee = false;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$product_ids = array( 1, 2, 3, 4 ); // Coma separated list of product id's that must be in cart for fee to apply
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
if ( in_array( $values['product_id'], $product_ids ) {
$apply_fee = true;
}
}
if ( $apply_fee ) {
$percentage = 0.01;
$surcharge = 10;
$woocommerce->cart->add_fee( 'Setup Fee', $surcharge, true, 'standard' );
}
}
?>
@DivaVocals
Copy link

I am getting the following error with this code:
PHP Parse error: syntax error, unexpected '{' in /mysite/public_html/wp-content/uploads/dynamik-gen/theme/custom-functions.php on line 150

Line 150 from my error log maps back to line 11 of this code snippet:
if ( in_array( $values['product_id'], $product_ids ) {

@numediaweb
Copy link

Missing closing parenthesis, change;

if ( in_array( $values['product_id'], $product_ids ) {

to

if ( in_array( $values['product_id'], $product_ids )) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment