Hi Tom,
Thank you for your patience, while I tested your website's data.
After thorough testing, I was able to make the following code work and you can replace it with the one in your theme's "functions.php" file:
/* Sortere eiendommer */
function auto_process_prices( $post_id ) {
if ( get_post_type( $post_id ) == 'eiendom' ) {
// get original price values with spaces
$price_1 = get_post_meta($post_id, 'wpcf-solgt-for', true);
$price_2 = get_post_meta($post_id, 'wpcf-overdratt-for', true);
$price_3 = get_post_meta($post_id, 'wpcf-andel-overdratt-for', true);
if (empty($price_1)) {
$price_1 = 0;
}
if (empty($price_2)) {
$price_2 = 0;
}
if (empty($price_3)) {
$price_3 = 0;
}
// remove empty spaces from the prices
$num_price_1 = str_replace(' ', '', $price_1);
$num_price_2 = str_replace(' ', '', $price_2);
$num_price_3 = str_replace(' ', '', $price_3);
if ($num_price_1 != 0) {
update_post_meta( $post_id, 'wpcf-solgt-for', $num_price_1, $price_1 );
}
if ($num_price_2 != 0) {
update_post_meta( $post_id, 'wpcf-overdratt-for', $num_price_2, $price_2 );
}
if ($num_price_3 != 0) {
update_post_meta( $post_id, 'wpcf-andel-overdratt-for', $num_price_3, $price_3 );
}
// get sum of all prices
$count = $num_price_1 + $num_price_2 + $num_price_3;
// update the sum in the Sum custom field
update_post_meta( $post_id, 'wpcf-sum', $count );
}
}
add_action( 'save_post', 'auto_process_prices', 99 );
To recap, the above block will perform these operations, step-by-step:
1. When a post of type "eiendom" will be saved/updated in the admin area, it will get the values of custom fields with slugs "solgt-for", "overdratt-for" and "andel-overdratt-for".
2. If those values will have an empty space, it will be removed and the respective custom field will be updated with space-free value.
3. The sum of all these 3 fields will be calculated and will be updated in the custom field with the slug "sum".
Tip: If you're interested in a code that performs all the above actions in bulk, for all existing published "eiendom" posts at once, you can check out the code for a custom shortcode at:
hidden link
To use it, you can add this to your theme's "functions.php" file temporarily and then add the shortcode [show-price-data] in a temporary page/post and view that page/post on the front-end. You'll see the updated data in a tabular format.
Important note: Since the effect of this shortcode will be permanent and irreversible, you should only use it if you're sure that what it does is really what is required and only after making a backup copy of the database.
Once the data has been updated, please remove the shortcode from the page/post where it was added and also from the "functions.php" file.
I hope this helps and let me know how it goes.
regards,
Waqar