Problem:
How to calculate the value of a custom field based on other custom fields values?
Solution:
Here is solution, please add the code in functions.php file:
function calculate_fields( $post_ID ) { if ( get_post_type( $post_ID ) == 'net-worth' ) { $total_assets = $total_liabilities = 0; // Assets $cash_on_hand = get_post_meta($post_ID, 'wpcf-ass-cash-on-hand', true); $checking_accounts = get_post_meta($post_ID, 'wpcf-ass-checking-accounts', true); $money_market_acc = get_post_meta($post_ID, 'wpcf-ass-money-market-accounts', true); // Libilities $credit_cards = get_post_meta($post_ID, 'wpcf-lib-credit-cards', true); $home_mortgages = get_post_meta($post_ID, 'wpcf-lib-home-mortgages', true); // Total Assets $total_assets = $cash_on_hand + $checking_accounts + $money_market_acc; update_post_meta( $post_ID, 'wpcf-total-assets', $total_assets ); // Total Liabilities $total_liabilities = $credit_cards + $home_mortgages; update_post_meta( $post_ID, 'wpcf-total-liabilities', $total_liabilities ); // Net Worth $net_worth = $total_assets - $total_liabilities; update_post_meta( $post_ID, 'wpcf-net-worth', $net_worth ); } } add_action( 'save_post', 'calculate_fields', 99 );
We need to add cred hook to call the calculation function. I have added the following code in custom functions.php file, and it is working as expected, see attached screenshot: https://cdn.toolset.com/wp-content/uploads/2017/09/569909-fields_calculated.png?x41285
add_action('cred_save_data', 'my_save_data_action',10,2); function my_save_data_action($post_id, $form_data) { // if a specific form if ($form_data['id']==1337) { calculate_fields( $post_id ); } }
This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.
Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.
Our next available supporter will start replying to tickets in about 4.73 hours from now. Thank you for your understanding.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
- | 12:00 – 17:00 | 12:00 – 17:00 | 12:00 – 17:00 | 12:00 – 17:00 | 12:00 – 17:00 | - |
- | 18:00 – 21:00 | 18:00 – 21:00 | 18:00 – 21:00 | 18:00 – 21:00 | 18:00 – 21:00 | - |
Supporter timezone: Asia/Karachi (GMT+05:00)
This topic contains 15 replies, has 2 voices.
Last updated by 7 years, 2 months ago.
Assisted by: Noman.