Hi waqar,
i have 2 number field[wpcf-property-size] , [wpcf-property-price]
i wan to perform calculation with it and store it in a custom field [wpcf-price-psf] (that/s already generated and has empty value) so when editing or creating new post, i wont have to enter the calculated field manually but upon saving the value will be updated accordingly. can you guide me on this pls. sample code will be very useful.
thanks.
Hi Dee,
Thanks for asking! I'd be happy to help.
To programmatically update a custom field's value (when a post is added or edited from the admin area), you can use "save_post" hook.
( ref: https://codex.wordpress.org/Plugin_API/Action_Reference/save_post )
We have a guide on the topic at:
https://toolset.com/documentation/customizing-sites-using-php/updating-types-fields-using-php/
Example:
add_action( 'save_post', 'auto_calc_field', 99 );
function auto_calc_field( $post_id )
{
if( get_post_type( $post_id ) == 'post-type-slug' ) {
$field_1 = get_post_meta($post_id, 'wpcf-field-slug-1', true);
$field_2 = get_post_meta($post_id, 'wpcf-field-slug-2', true);
$field_3 = get_post_meta($post_id, 'wpcf-field-slug-3', true);
// do the actual processing
$processed_value = $field_1 + $field_2;
update_post_meta( $post_id, 'wpcf-field-slug-3', $processed_value, $field_3 );
}
}
Note: You'll need to update the "post-type-slug" and the custom field slugs (with "wpcf-") to match the actual values from your website.
I hope this helps.
regards,
Waqar
My issue is resolved now. Thank you!