Last active
October 15, 2018 08:53
-
-
Save michaeltieso/4f296f1156b6def582200ea88770a395 to your computer and use it in GitHub Desktop.
Displays bulk pricing rules on product pages from WooCommerce Dynamic Pricing.
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
function mdt_woo_pricing_rules() { | |
global $post; | |
$pricing_rule_sets = apply_filters( 'dynamic_pricing_product_rules', get_post_meta( $post->ID, '_pricing_rules', true ) ); | |
if ( ! is_array( $pricing_rule_sets ) ) { | |
return [ ]; | |
} | |
$product = new WC_Product(get_the_ID()); | |
$price = $product->get_price(); | |
$conditions_met = 0; | |
$discount = [ ]; | |
$count = 0; | |
foreach ( $pricing_rule_sets as $pricing_rule_set ) { | |
static $num_decimals; | |
if($num_decimals === NULL) | |
$num_decimals = apply_filters( 'woocommerce_dynamic_pricing_get_decimals', (int) get_option( 'woocommerce_price_num_decimals' ) ); | |
foreach ( $pricing_rule_set['rules'] as $key => $rule ) { | |
extract($rule); | |
$result = $price; | |
switch ( $type) { | |
case 'price_discount': | |
$adjusted = floatval( $price ) - floatval( $amount ); | |
$result = $adjusted >= 0 ? $adjusted : 0; | |
break; | |
case 'percentage_discount': | |
if ( $amount > 1 ) { | |
$amount = $amount / 100; | |
} | |
$result = round( floatval( $price ) - ( floatval( $amount ) * $price), (int) $num_decimals ); | |
break; | |
case 'fixed_price': | |
$result = round( $amount, (int) $num_decimals ); | |
break; | |
default: | |
$result = false; | |
break; | |
} | |
if($result == 0) | |
continue; | |
$discount[ $count ] = new stdClass(); | |
$from = $rule['from']; | |
$to = $rule['to']; | |
$discount[ $count ]->qty = ! empty( $to ) ? "$from – $to" : "$from+"; | |
$discount[ $count ]->price = wc_price($result); | |
$count ++; | |
} | |
} | |
return $discount; | |
} | |
function mdt_change_product_price_display( $price ) { | |
global $product; | |
if ( is_archive() || is_page() ) { | |
$discounts = mdt_woo_pricing_rules(); | |
$price = !empty($discounts) ? 'From ' . array_pop($discounts)->price : wc_price($product->get_price()); | |
return $price; | |
} | |
else { | |
$price = '$' . $product->get_price() . ' Per Item'; | |
return $price; | |
} | |
} | |
add_filter( 'woocommerce_get_price_html', 'mdt_change_product_price_display' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment