Last active
November 3, 2022 22:12
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Combine this with this code to create a currency field from standard text field:
https://gist.github.com/tripflex/d49cc84fc05c77cf9662