I have a meta key called ‘prijs’ in each post. The value of this meta key consist of numbers in the follow structure: 2,100.00
I want to remove the comma in the meta value to get this output: 2100.00
So, i created a function but it doesn’t work:
add_action('wp_insert_post', 'deleteCommaDB');
function deleteCommaDB($postID){
$price_key = 'prijs';
$getPrice = get_post_meta($postID, $price_key, true);
$newPrice = str_replace(array(','), '', $getPrice);
update_post_meta($postID, $price_key, $newPrice);
return true;
}
I created the function deleteCommaDB
. This function gets the post meta from the meta key ‘prijs’, and replaces the comma for nothing. This new value is saved in the variable $newPrice. Next thing to do, is update the post meta with the new value.
What am i doing wrong?
You’ll only need to run it once, but this should get all your posts, and then loop through them and update the meta.
Your function runs only when a post is inserted. You might want to consider running on
save_post
and sanitizing the$_POST
input in the first place.add_action(‘wp_insert_post’, ‘deleteCommaDB’); – this line calls your function only on post creation.
In order to change all previously saved posts, you will need to add your function in a wordpress loop that gets all the posts.
Always take the right tool for the right job
No need for
str_replace()
and other complicated or slow things. Use what PHP or WordPress deliver for such cases:number_format_i18n()
number_format()
For the record: There’s also a function called
money_format()
.