Field editor output value formatted as currency (when using auto output, shortcode, or widget)

functions.php

<?php
// ^ the <?php above should only be in your functions.php file ONCE, at the top

// The filter is field_editor_output_as_value_METAKEY
// where you need to replace METAKEY with the actual meta key you want to filter the output for
// .... as you can see below you can also add multiple filters using the same function.
add_filter( 'field_editor_output_as_value_METAKEY', 'my_custom_format_value_as_currency' );
add_filter( 'field_editor_output_as_value_ANOTHERMETAKEY', 'my_custom_format_value_as_currency' );

/**
 * General function to output HTML for custom fields
 *
 * @author             Myles McNamara
 * @url                https://plugins.smyl.es
 *
 * @param    $value    The value before it is output on the listing
 */
function my_custom_format_value_as_currency( $value ){
	if( empty( $value ) ) return $value;
	// We have to set the locale so PHP knows how to format the value
	// http://php.net/manual/en/function.setlocale.php
	// this tells PHP to use $ and format based on english US
	setlocale(LC_MONETARY, 'en_US');
	
	// 0n means output 0 decimal places, to output 2 decimal, change to 2n
	// http://php.net/manual/en/function.money-format.php
	// If the value was 10123.44, the output would be $10,123
	return money_format('%.0n', $value);
}
No comments yet.

Leave a Reply