Skip to content

Instantly share code, notes, and snippets.

@Frisoni
Last active November 20, 2018 16:41
Show Gist options
  • Save Frisoni/7bdf2c7b6af14d6f16415756fff3a563 to your computer and use it in GitHub Desktop.
Save Frisoni/7bdf2c7b6af14d6f16415756fff3a563 to your computer and use it in GitHub Desktop.
/**
* Calculates discount percentage for the product sale bubble for
* simple, variable or external product types. Returns base bubble text
* with or without formatting otherwise.
*
* @param $product
*
* @return string
*/
function flatsome_presentage_bubble( $product ) {
// WC Dynamic compatible
if (class_exists('WC_Dynamic_Pricing')) {
$dynamic_pricing = WC_Dynamic_Pricing::instance();
}
if ( $product->is_type( 'simple' ) || $product->is_type( 'external' ) ) {
$regular_price = $product->get_regular_price();
$sale_price = $product->get_sale_price();
// WC Dynamic compatible
if (class_exists('WC_Dynamic_Pricing')) {
$sale_price = $dynamic_pricing->on_get_price( $regular_price, $product, false );
}
$bubble_content = round( ( ( floatval( $regular_price ) - floatval( $sale_price ) ) / floatval( $regular_price ) ) * 100 );
} elseif ( $product->is_type( 'variable' ) ) {
$available_variations = $product->get_available_variations();
$maximumper = 0;
for ( $i = 0; $i < count( $available_variations ); ++ $i ) {
$variation_id = $available_variations[ $i ]['variation_id'];
$variable_product = new WC_Product_Variation( $variation_id );
if ( ! $variable_product->is_on_sale() ) {
continue;
}
$regular_price = $variable_product->get_regular_price();
$sale_price = $variable_product->get_sale_price();
// WC Dynamic compatible
if (class_exists('WC_Dynamic_Pricing')) {
$sale_price = $dynamic_pricing->on_get_price( $regular_price, $variable_product, false );
}
$percentage = round( ( ( floatval( $regular_price ) - floatval( $sale_price ) ) / floatval( $regular_price ) ) * 100 );
if ( $percentage > $maximumper ) {
$maximumper = $percentage;
}
}
$bubble_content = sprintf( __( '%s', 'woocommerce' ), $maximumper );
} else {
// Set default and return if the product type doesn't meet specification.
$bubble_content = __( 'Sale!', 'woocommerce' );
return $bubble_content;
}
// Process custom formatting. Keep mod value double check to process % for default parameter (See sprintf()).
$formatting = get_theme_mod( 'sale_bubble_percentage_formatting' );
$formatting = $formatting ? $formatting : '-{value}%';
$bubble_content = str_replace( '{value}', $bubble_content, $formatting );
return $bubble_content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment