Remove Price from Subscription Product Which Offers Free Trial At Cart & Checkout

This code removes the subscription price of any product created using the official WooCommerce Subscriptions plugin. The price is removed from the cart and checkout page subtotals and totals as well as the cart item table.

In this example, we target subscriptions products with a 7 day free trial. All other subscriptions products remain unaffected by this code.

Here’s the before and after screenshots for the cart page showing the price included and then removed from the subtotals and totals once the code is added.

And also on the checkout page :

In summary, this code works using a WooCommerce Subscription product with a 7-day free trial where the user sees a price of $0 at checkout and then the annual subscription price at the end of the free trial period.

Demo Video

How The Code Works

There’s 3 functions included in the code do the following :

  1. Get the trial length of a subscription product by product ID
  2. Check if the product has a 7-day free trial
  3. Modify cart items to set price to 0 for products with a 7-day free trial

Code Installation

Copy and paste the PHP code to the end of your child themes functions file or custom functionality/code snippets plugin.

Download Folder

Developers

Here’s an explanation how each function in the code works :

1. customize_cart_item_price($cart) :

  • This function is hooked to the woocommerce_before_calculate_totals action. It runs when WooCommerce is calculating the cart totals.
  • It loops through each item in the cart.
  • For each cart item, it checks whether it has a 7-day free trial using the has_seven_day_free_trial function.
  • If the product has a 7-day free trial, it sets the price of the cart item to 0 using $cart_item['data']->set_price(0). This essentially makes the product free in the cart for the duration of the trial.

2. has_seven_day_free_trial($product_id) :

  • This function checks if a product has a 7-day free trial.
  • It takes the $product_id as an argument.
  • It retrieves the product information using wc_get_product($product_id).
  • If the product is a subscription product (checked with $product->is_type('subscription') ), it proceeds to check if the trial length is 7 days using the get_subscription_trial_length function.
  • If the trial length is indeed 7 days, it returns true, indicating that the product has a 7-day free trial. Otherwise, it returns false.

3. get_subscription_trial_length($product_id) :

  • This function retrieves the trial length of a subscription product by its product ID.
  • It takes the $product_id as an argument.
  • It uses get_post_meta($product_id, '_subscription_trial_length', true) to fetch the trial length from the product’s post meta.
  • It converts the trial length to an integer using intval and returns the result.

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.