Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JeroenSormani/46d41cdc31c1ff2ed85e to your computer and use it in GitHub Desktop.
Save JeroenSormani/46d41cdc31c1ff2ed85e to your computer and use it in GitHub Desktop.
A compatibility function to make Advanced Product Labels and Dynamic Pricing work nicely together (percentage discount)
<?php
/**
* WooCommerce Advanced Product Labels / Dynamic Pricing smart labels
*/
function dynamic_pricing_advanced_product_labels_compat( $label ) {
global $product;
if ( ! $product ) :
$product_posts = get_posts( array( 'post_type' => 'product', 'posts_per_page' => 1 ) );
$product = reset( $product_posts );
endif;
$product = wc_get_product( $product );
if ( class_exists( 'WC_Dynamic_Pricing' ) ) {
$pricing = WC_Dynamic_Pricing::instance();
if ( apply_filters( 'wc_dynamic_pricing_get_use_sale_price', true, $product ) ) {
$working_price = $product->get_price();
} else {
$working_price = $product->get_regular_price();
}
$d_price = $pricing->on_get_price($working_price, $product, true );
if ($d_price != $working_price && ( empty($sale_price) || $d_price < $sale_price)) {
$regular_price = $working_price;
$sale_price = $d_price;
}
$percentage = null;
if ( ! empty( $regular_price ) && $regular_price != 0 ) :
$percentage = ( $regular_price - $sale_price ) / $regular_price * 100;
endif;
if ( ! is_null( $percentage ) ) :
$label = str_replace( '{percentage}', round( $percentage, apply_filters( 'wapl_filter_discount_round', 1 ) ) . '%', $label );
endif;
if ( ! empty( $regular_price ) && $regular_price != 0 ) :
$label = str_replace( '{discount}', sprintf( get_woocommerce_price_format(), get_woocommerce_currency_symbol(), ($regular_price-$sale_price) ), $label );
$label = str_replace( '{price}', sprintf( get_woocommerce_price_format(), get_woocommerce_currency_symbol(), $regular_price ), $label );
$label = str_replace( '{saleprice}', sprintf( get_woocommerce_price_format(), get_woocommerce_currency_symbol(), $sale_price ), $label );
$label = str_replace( '{delprice}', '<del>'.sprintf( get_woocommerce_price_format(), get_woocommerce_currency_symbol(), $regular_price ) . '</del>', $label );
endif;
}
return $label;
}
add_action( 'wapl_product_label', 'dynamic_pricing_advanced_product_labels_compat', 9 );
@anteajac
Copy link

anteajac commented Oct 2, 2015

Fatal error: Call to a member function get_price() on a non-object in C:\xampp\htdocs\xxx\wp-content\themes\xxx-child\functions.php on line 95

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