Skip to content

Instantly share code, notes, and snippets.

@badabingbreda
Last active October 25, 2018 20:36
Show Gist options
  • Save badabingbreda/f6383a1ccece89fd43dba5d383ca3198 to your computer and use it in GitHub Desktop.
Save badabingbreda/f6383a1ccece89fd43dba5d383ca3198 to your computer and use it in GitHub Desktop.
ACF number format with classes
<?php
/**
* return number_formatted fieldvalue by adding classes to number field in Field Group
*
* my-currency : return as formatted number 1999 becomes 1,999
* my-currency-dec-# : set the number of decimals to return, # is the number of decimals (needs at least one character)
*/
add_filter( 'acf/load_value/type=number', 'my_check_number_classes', 10, 3 );
function my_check_number_classes( $value , $post_id , $field ){
if ( is_admin() ) return $value;
$re = '/(?:my\-currency\-dec\-)([0-9]{1,})|(?:my-currency)\b/m';
preg_match_all($re, $field['wrapper']['class'], $matches, PREG_SET_ORDER, 0);
// if there are no matches at all return asap
if (!$matches) return $value;
// set defaults
$do_number_format = false;
$decimals = 0;
if (sizeof( $matches ) > 0 ) {
foreach ($matches as $match) {
switch ( $match[0] ) {
case 'my-currency':
$do_number_format = true;
break;
// must be a match for my-currency-dec-#
default:
$decimals = (integer)$match[1];
break;
}
}
}
// if a my-currency class was found return as number_format
if ( $do_number_format ) return number_format( $value , $decimals , '.' , ',');
// if after all no my-currency class was found simple return the value
return $value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment