I have woocommerce subscriptions plugin setup with a variable subscription product with attributes called ‘Plan’ and free trial (15 days) in the WP admin. I have programmatically added a custom field (multiple select dropdown) on he frontend called ‘Location’ and it looks like this-
Now, if someone tries to buy a subscription for a location they have already bought in the past, then I programmatically remove the free trial of 15 days when they add it to cart. The code for this is below (which works fine for buying new subscription)-
add_action( 'woocommerce_before_calculate_totals', 'update_cart_item_price_from_custom_field', 10, 1 );
// Update cart item price based on custom field value
function update_cart_item_price_from_custom_field( $cart_object ) {
if (is_admin() && !defined('DOING_AJAX')) {
return;
}
if ( did_action( 'woocommerce_before_calculate_totals' ) > 1 ) return;
// Iterate through the cart items
foreach ($cart_object->get_cart() as $cart_item_key => $cart_item) {
$product = $cart_item['data'];
$trial_length = $product->get_meta('_subscription_trial_length', true);
$location_id = $cart_item['Location_id'] ? (array)$cart_item['Location_id'] : array();
// Check if product is a subscription and has a trial
if ($product->is_type('subscription_variation') && $trial_length > 0 && !empty($location_id)) {
$user_id = get_current_user_id();
$product_id = $product->get_parent_id(); //$cart_item['product_id'];
$variation_id = $product->get_id(); //$cart_item['variation_id'];
// Check if user has already taken the trial for this location_id
$has_taken_trial = check_user_trial($user_id, $location_id, $product_id); //this is a custom function
if ($has_taken_trial != null) {
// Remove the trial
$cart_item['data']->update_meta_data('_subscription_trial_length', 0);
}
}
}
}
This works fine for new subscription orders, but when trying to switch a subscription during a free trial and adding locations to it (that would trigger free trial removal), above code doesn’t have any effect on free trial (that is it should have $$$ due today).
Although when I checked ‘_subscription_trial_length’ in cart, it is set to zero for subscription switch and yet no change to cart due date.
Here is a link to woocommerce subscription switching logic and I believe woocommerce internally creates new subscription based on what things are changed.
Anyone have any idea on how to access the properties of switch subscription and remove free trial. TIA