Code Example: Calculate the Autoship Discount Based on Sale Price

(src/products.php) In this example the dev changes the displayed discount percentage on product pages relative to the (WooCommerce) sale price of an item (if one exists). 

/**
* Adjust Autoship Discount String so text shows percentages ( Checkout & Recurring )
* based off sale price not regular. If no sale price exists the discount percentages
* will be calculated off Regular price.
*
* NOTE IMPORTANT - This adjusts the text only.  It's important that the
* values entered for the Checkout and Recurring prices are entered
* relative to the Sale price.
* @param array $prices The current product/variation prices and discount pct.
* @param int $product_id The WC_Product id.
* @param WC_Product $product The woocommerce product.
*
* @return array The filtered prices array.
*/
function xx_autoship_adjust_discount_string( $prices, $product_id, $product ){

  // If a sale price exists adjust the checkout pct discount based off that.
  if ( isset( $prices['sale_price'] ) && !empty( $prices['sale_price'] ) )
  $prices['autoship_percent_discount'] = 100 - round( ( $prices['autoship_checkout_price'] / $prices['sale_price'] ) * 100 , 2 );

  // If a sale price exists adjust the recurring pct discount based off that.
  if ( isset( $prices['sale_price'] ) && !empty( $prices['sale_price'] ) )
  $prices['autoship_percent_recurring_discount'] = 100 - round( ( $prices['autoship_recurring_price'] / $prices['sale_price'] ) * 100 , 2 );

  return $prices;

}
add_filter('autoship_all_prices_array', 'xx_autoship_adjust_discount_string', 10, 3 );


In the images below, see how the Autoship Discount Amount displays 22% in the 'Before' image and 10.41% in the 'After' image? This is due to the change in price referenced when the discount is calculated from the (WooCommerce) Regular Price to the (WooCommerce) Sale Price. In addition, the 'After' image shows the (WooCommerce) Sale Price with the strikethrough when the Autoship option is selected. 

Before

After

Still need help? Contact Us Contact Us