Quantcast
Channel: Code Snippets – Code My Own Road
Viewing all articles
Browse latest Browse all 8

How To Add Currency Code As Suffix To Prices In WooCommerce

$
0
0

WooCommerceIf you’re looking for a way to modify the price so that your currency code becomes a suffix to your prices in WooCommerce you’ve come to the right code snippet tutorial.

I’m going to show you how to make prices that look like this:

$49

Into this:

$49 AUD

When I was relaunching my site for ThirstyAffiliates we brought the shopping cart experience home with WooCommerce.

During the process I changed my pricing to AUD (Australian Dollars) but because the currency symbol ($) is the same as USD I thought it might cause some confusion if the first place they saw AUD was in PayPal when they got through to process their payment.

I’ve written previously about changing the currency symbol in WooCommerce to include your currency code, but it leaves the prices looking a little unnatural like this “AUD$49”.

The first step is easy enough, create a function to filter the price format in WooCommerce.

WooCommerce makes this ridiculously easy with it’s ample hooks and filters API, we just jump into the “woocommerce_price_format” action.

Here’s the code snippet which will add the suffix to all your prices throughout the site (copy and paste into your functions.php):

function addPriceSuffix($format, $currency_pos) {
	switch ( $currency_pos ) {
		case 'left' :
			$currency = get_woocommerce_currency();
			$format = '%1$s%2$s ' . $currency;
		break;
	}
 
	return $format;
}
 
add_action('woocommerce_price_format', 'addPriceSuffix', 1, 2);

I also wanted the ability to just show the currency code suffix on prices in the cart and checkout pages, leaving my product pages and listings all unaffected.

To do this you need to wrap this add_action with another function that only gets called on those pages.

We use two new actions to call our function to add the action for modifying the price format. Tricky stuff!

Here’s the full code snippet for restricting the formatting to cart and checkout (copy and paste into your functions.php):

function addPriceSuffix($format, $currency_pos) {
	switch ( $currency_pos ) {
		case 'left' :
			$currency = get_woocommerce_currency();
			$format = '%1$s%2$s ' . $currency;
		break;
	}
 
	return $format;
}
 
function addPriceSuffixAction() {
	add_action('woocommerce_price_format', 'addPriceSuffix', 1, 2);
}
 
add_action('woocommerce_before_cart', 'addPriceSuffixAction');
add_action('woocommerce_review_order_before_order_total', 'addPriceSuffixAction');

Hope this helps you, if it does feel free to leave a comment :)


Viewing all articles
Browse latest Browse all 8

Trending Articles