If you are selling subscriptions with WooCommerce, you are probably using WooCommerce Subscriptions to do so. And if you are using it, you already know the structure of the price string for subscription products.
It’s really hard to create a valid price string when you are selling subscriptions. There are a lot of factors to consider, like free trials, intervals, etc.
The developers handle this properly, but sometimes, it’s not correct for what you sell or your store workflow.
You can change the price string, but it could be more complex than it seems.
In this article we’ll cover three code samples to change the price string in three different cases.
How does it work?
We’ll use the PHP function str_replace
to handle the changes. We will use arrays of product IDs when necessary to change the string only on some products.
All the snippets need to be added in the file functions.php located in wp-content/themes/your-theme-name/, at the end of the file.
The example is on a product that is renewed every 3 months, without a free trial or sign-up fee.
Change the string globally
In the first example we’ll change the string for all the subscription products in the store. The code to do so is:
function wc_subscriptions_custom_price_string( $pricestring ) {
$newprice = str_replace( ‘every 3 months’, ‘per season’, $pricestring );
return $newprice;
}
add_filter( ‘woocommerce_subscriptions_product_price_string’, ‘wc_subscriptions_custom_price_string’ );
add_filter( ‘woocommerce_subscription_price_string’, ‘wc_subscriptions_custom_price_string’ );
The two filters used will change the price string everywhere, both in the product single page and the cart page.
Change the string only on some products
This example will change the price string only on the product single page and only on some products:
function wc_subscriptions_custom_price_string( $pricestring ) {
global $product;
$products_to_change = array( 45, 90, 238 );
if ( in_array( $product->id, $products_to_change ) ) {
$pricestring = str_replace( ‘every 3 months’, ‘per season’, $pricestring );
}
return $pricestring;
}
add_filter( ‘woocommerce_subscriptions_product_price_string’, ‘wc_subscriptions_custom_price_string’ );
Handle complex strings
In some cases, in example if you have a free trial or/and a sign-up fee, the price string will be more complex.
If this is your case, you can copy/paste the line where we use str_replace
and change the words to change the other parts of the string, like in this example:
function wc_subscriptions_custom_price_string( $pricestring ) {
$pricestring = str_replace( ‘every 3 months’, ‘per season’, $pricestring );
$pricestring = str_replace( ‘sign-up fee’, ‘initial payment’, $pricestring );
return $pricestring;
}
add_filter( ‘woocommerce_subscriptions_product_price_string’, ‘wc_subscriptions_custom_price_string’ );
add_filter( ‘woocommerce_subscription_price_string’, ‘wc_subscriptions_custom_price_string’ );