Skip to content

Instantly share code, notes, and snippets.

@Ezep
Last active August 29, 2016 04:31
Show Gist options
  • Save Ezep/f66cd19aac0fc1f7bfd4eaa161dec059 to your computer and use it in GitHub Desktop.
Save Ezep/f66cd19aac0fc1f7bfd4eaa161dec059 to your computer and use it in GitHub Desktop.
Woocommerce Discount/Fee from custom attribute
function ezep_cart_order_total_action(WC_Cart $cart){
global $woocommerce, $post;
$order = new WC_Order($post->ID);
$order_items = $woocommerce->cart->get_cart();
$discount = 0;
$discount_name = "Descuento por pago en efectivo";
$payment_method = "";
$payment_method_desired = "cod";
$attribute_desired = "pa_cash_price";
if (isset($_POST['payment_method'])){
$payment_method = $_POST['payment_method'];
}
if ($payment_method == $payment_method_desired){
foreach ($order_items as $order_item_key => $order_item) {
$_product = new WC_Product( $order_item['data']->post->ID );
$quantity = $order_item['quantity'];
$cash_price = 0;
$cash_price = $_product->get_attribute( $attribute_desired );
if ($cash_price){
$price = $_product->price;
$discount += ( floatval($price) - floatval($cash_price) ) * $quantity ;
}
}
if(!empty($discount) || $discount != 0){
$discount *= -1; // convert positive to negative fees
$woocommerce->cart->add_fee(__($discount_name,"woocommerce"), $discount, false, "" ); // add negative fees
}
}
}
add_action('woocommerce_cart_calculate_fees', 'ezep_cart_order_total_action');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment