Autoship Cloud Dynamic Checkout Price Based on Selected Frequency
In this example, a developer adjusts the Autoship Checkout price based on the selected frequency of their Autoship Items. The result is a discounted Autoship Checkout Price in the Cart and Checkout being used for 3, 4, and 5 month frequencies for a specific product.
Remember: always test new code on a staging site before adding it to your live site
Code:
<?php
/**
* Applies a custom checkout price to a specific product with a frequency type and number
* otherwise returns original checkout price.
* @param float $checkout_price. The current discounted or not checkout price for this autoship product.
* @param int $product_id. The current product's id.
* @param string $frequency_type. The Autoship frequency type ( Months, Days, etc ).
* @param int $frequency. The frequency value.
*
* @return float. The new calculated checkout price or the originally supplied
*
*/
function xx_dynamic_autoship_checkout_price( $checkout_price, $product_id, $frequency_type, $frequency ){
// Simple example checks for if this is a special product id.
if ( 9 == $product_id ){
$product = wc_get_product( $product_id );
$original_price = $product->get_price();
// Generate a switch key.
$key = $frequency_type . '-' . $frequency;
$discounts = array(
'Months-3' => .1,
'Months-4' => .25,
'Months-5' => .4,
);
// Easy case just check if this is a discounted combo
// If so return new calculated checkout price.
// If not return original checkout price.
if ( isset( $discounts[$key] ) ) {
return (int)( ( $original_price - ($original_price * $discounts[$key]) ) * 100 ) / 100;
} else {
return $checkout_price;
}
}
return $checkout_price;
}
add_filter( 'autoship_checkout_price', 'xx_dynamic_autoship_checkout_price', 10, 4 );
Frequency: 4 Months Selected
