Skip to content

Instantly share code, notes, and snippets.

@tripflex
Last active November 3, 2022 22:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tripflex/849295c2c2a59a92585a to your computer and use it in GitHub Desktop.
Save tripflex/849295c2c2a59a92585a to your computer and use it in GitHub Desktop.
Field editor output value formatted as currency (when using auto output, shortcode, or widget)
<?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' );
// Just uncomment the code below to use same handling for a different meta key
//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
$fmt = numfmt_create( 'en_US', NumberFormatter::CURRENCY );
// You MAY need to use en_US.UTF-8 if the above is not working
// Make sure to remove currency symbol and any commas
$value = str_replace( array( '$', ',' ), '', $value );
// Make sure to convert to useable value (in case using formatting on frontend)
$value = floatval( $value );
// Currency code from https://en.wikipedia.org/wiki/ISO_4217
return numfmt_format_currency($fmt, $value, "USD");
}
@tripflex
Copy link
Author

tripflex commented Jan 8, 2018

Combine this with this code to create a currency field from standard text field:
https://gist.github.com/tripflex/d49cc84fc05c77cf9662

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment