Hi,
I have 3 custom fields a, b and c. They are all text field and only allow to enter numbers.
1. Can it automatically set c value by the formula of a divided by b?
2. Can the above design apply for creating and editing a custom post type?
Hello,
There isn't such kind of built-in feature within Toolset Types plugin, you will consider custom codes, for example:
1) When user create/edit a custom post, use action hook "save_post" to trigger a PHP function:
https://developer.wordpress.org/reference/hooks/save_post/
2) In this PHP function, get the custom field "b" value:
https://developer.wordpress.org/reference/functions/get_post_meta/
Use it to calculate the field "c" value, and update field "c"
https://developer.wordpress.org/reference/functions/update_post_meta/
One more thing, the Toolset Types plugin will add string "wpcf-" before field slug, for example custom field "c", in database, the field slug is "wpcf-c".
function update_discount_percent() {
$posId = get_the_ID();
$current_Price = get_post_meta( $posId, 'wpcf-cf-current-price', true ) ;
$RRP = get_post_meta( $posId, 'wpcf-cf-rrp-common', true ) ;
if (!empty($RRP) && !empty($current_Price))
update_post_meta($posId, 'wpcf-cf-discount-percent', round(($RRP - $current_Price) / $RRP * 100)) ;
}
add_action( 'save_post', 'update_discount_percent' );
get_post_meta and update_post_meta work as expected. but add_action( 'save_post') doesn't work. No matter I create a new post or edit an existing post.
Since it is a custom codes problem, if you need more assistance for it, please provide a test site, fill below private message box with login details, also point out:
1) The problem page/post URL
2) Where I can edit your PHP codes
Thanks for the details, it is also a Toolset post form, so you can use form API action hook cred_save_data, I have changed the PHP codes as below:
function update_discount_percent($post_id, $form_data) {
if ($form_data['id']!=129) return;
$current_Price = get_post_meta( $post_id, 'wpcf-cf-current-price', true ) ;
$RRP = get_post_meta( $post_id, 'wpcf-cf-rrp-common', true ) ;
if (!empty($RRP) && !empty($current_Price))
update_post_meta($post_id, 'wpcf-cf-discount-percent', round(($RRP - $current_Price) / $RRP * 100)) ;
}
add_action( 'cred_save_data', 'update_discount_percent', 10, 2);
Please test again, check if it is fixed.
More help:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data
My issue is resolved now. Thank you!