Automattic\WooCommerce\Admin\API

MarketingCampaigns::get_formatted_price()privateWC 1.0

Get formatted price based on Price type.

This uses plugins/woocommerce/i18n/currency-info.php and plugins/woocommerce/i18n/locale-info.php to get option object based on $price->currency.

Example:

  • When $price->currency is 'USD' and $price->value is '1000', it should return '$1000.00'.
  • When $price->currency is 'JPY' and $price->value is '1000', it should return '¥1,000'.
  • When $price->currency is 'AED' and $price->value is '1000', it should return '5.000,00 د.إ'.

Method of the class: MarketingCampaigns{}

No Hooks.

Return

String. formatted price.

Usage

// private - for code of main (parent) class only
$result = $this->get_formatted_price( $price );
$price(Price) (required)
Price object.

MarketingCampaigns::get_formatted_price() code WC 9.0.1

private function get_formatted_price( $price ) {
	// Get $num_decimals to be passed to wc_price.
	$locale_info_all = include WC()->plugin_path() . '/i18n/locale-info.php';
	$locale_index    = array_search( $price->get_currency(), array_column( $locale_info_all, 'currency_code' ), true );
	$locale          = array_values( $locale_info_all )[ $locale_index ];
	$num_decimals    = $locale['num_decimals'];

	// Get $currency_info based on user locale or default locale.
	$currency_locales = $locale['locales'];
	$user_locale      = get_user_locale();
	$currency_info    = $currency_locales[ $user_locale ] ?? $currency_locales['default'];

	// Get $price_format to be passed to wc_price.
	$currency_pos     = $currency_info['currency_pos'];
	$currency_formats = array(
		'left'        => '%1$s%2$s',
		'right'       => '%2$s%1$s',
		'left_space'  => '%1$s %2$s',
		'right_space' => '%2$s %1$s',
	);
	$price_format     = $currency_formats[ $currency_pos ] ?? $currency_formats['left'];

	$price_value     = wc_format_decimal( $price->get_value() );
	$price_formatted = wc_price(
		$price_value,
		array(
			'currency'           => $price->get_currency(),
			'decimal_separator'  => $currency_info['decimal_sep'],
			'thousand_separator' => $currency_info['thousand_sep'],
			'decimals'           => $num_decimals,
			'price_format'       => $price_format,
		)
	);

	return html_entity_decode( wp_strip_all_tags( $price_formatted ) );
}