I need to format a custom field in admin area (post edit) as a currency, eq: 12.000,00 , with user typing only the numbers, the , and . automatic. Ive searched arround, with no sucess.. Anyone? thank
The code i am trying to use to enqueue script in admin is
function enqueue_admin() {
wp_enqueue_script( 'jquery' ); //adding Jquery to admin. Not sure if is needed or already there
wp_register_script( 'autonum', THEME_DIR . '/js/vendor/autoNumeric.js', array( 'jquery' ), '1', false ); //this is autoNumeric for currency format
wp_enqueue_script( 'autonum' );
}
add_action( 'admin_enqueue_scripts', 'enqueue_admin' );
Also, not sure if i need to change all the $ to JQuery in autoNumeric.js, because of wordpress compatibility
if you want to process the field after submitting, php’s number_format function is what you need:
but if you want to change how the number is displayed as it’s typed in, try jQuery autoNumeric
Autonumeric is a jQuery plugin and looks to be written so that you don’t have to swap out the
$
.I think the problem is this line:
The problem is that I am not sure where
THEME_DIR
is coming from. That constant is not defined on my test install. I suspect that you have a broken URL for that script.At any rate, even if
THEME_DIR
is defined and I just missed it, instead of that constant you should probably be usingget_template_directory_uri()
if this is a standalone, or parent, theme orget_stylesheet_directory_uri()
if it is a child theme.You can also use the WordPress function number_format_i18n which use the user locale to format the value.
Also, DO NOT USE the PHP money_format function because it is marked as deprecated in the PHP documentation.
I think is better, that you add with a plugin a meta box for your price field. There is easy to filter and format the output. The sore inside the database and it is easier to maintance or add the values inside the field for authors. For read, get output the value can you also use the default functions of custom post type. It give many tutorials and answers on WPSE to this topic.
For the format with php it is easy, if you use the
money_format()
function.echo money_format('$%i', 3.4); // echos '$3.40'
I think this function is the right way. The function use the locale var from the WordPress install and and works with different types and languages. A format with the default php functions is not usable for longer time, is the hard way to format in this context.
If you like a way in javascript, then see on this WPSE thread, very helpfull. But I think, the php way is fast and easy for a output inside a custom field, like in a Meta box.