Skip Navigation

[Resolved] Calculate value of a custom field based on other custom fields values

This thread is resolved. Here is a description of the problem and solution.

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 );
    }
}

100% of people find this useful.

This support ticket is created 7 years, 2 months ago. There's a good chance that you are reading advice that it now obsolete.

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 7.18 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 davidZ-4 7 years, 2 months ago.

Assisted by: Noman.

Author
Posts
#567676

Tell us what you are trying to do? Calculate the value of a custom field based on other custom fields values

Is there any documentation that you are following? I searched the Toolset Professional Support for the last week for a solution on calculations

Is there a similar example that we can see? some what similar https://toolset.com/forums/topic/can-i-display-the-sum-from-numbers-in-custom-fields-with-customize-conditions/ but not exact

What is the link to your site? hidden link

I created a custom post with custom fields in it all are number type
I have 3 fields that I want to calculate and store in the custom post. if the other numbers are changing the calculated fields will be updated automatically.

Total assets = sum of all assets
Total liabilities = Sum of all liabilities
Net Worth = Total assets - Total liabilities

each asset or liability is entered manually when saving/editing/updating the post type numbers I want the 3 calculations to be updated and insert the new numbers into the respective custom field

I have added the fallowing to my function file

// to allow for adding up totals in fields
global $total;
add_shortcode('add-to-total', 'add_total_shortcode');
function add_total_shortcode($atts, $content = '') {
global $total;
$string = str_replace('$', '', $string);
$total += wpv_do_shortcode($content);
}
add_shortcode('show-total', 'show_total_shortcode');
function show_total_shortcode() {
global $total;
$totalNew = $total;
return $totalNew;
}
// to allow math calculations on multiple fields
add_shortcode('wpv-calculate', 'calculate_shortcode');
function calculate_shortcode($atts) {
return wpv_condition($atts);
}

Please advise
thanks,

David

#567856

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Hi David,

Thank you for contacting Toolset support. Please confirm the following points:

1. You have 3 custom fields, want to calculate these 3 fields and then store the result in 4th field?
2. If any of the 3 custom fields update, then result field automatically update?

To achieve this I need to request you to please provide temporary access (WP-Admin and FTP Login info) to your site (preferably staging site), so that I can look into your setup and check the issue.

Your next answer will be private which means only you and I have access to it.

=== Please backup your database and website ===

✙ I would additionally need your permission to de-activate and re-activate Plugins and the Theme, and to change configurations on the site. This is also a reason the backup is really important.

✙ Please add the links where these fields are created

Thank you

#568668

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Verification code.png

Hello David,

Sorry we ran into the weekend. The login info you have provided is not working, actually its asking for verification code when I try to login and I am not sure which email it sends the verification - see attached screenshot.

Please provide working login. Thank you

#568760

oh, I forgot the about the Two-Factor Authentication.
I disabled it an now you should be able to login without the verification code.

Please let me know if you have any issue.

Thanks,
David

#568823

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Financial Data.png

Thanks, login works now, I have taken a look at your setup and fields. I need some clarifications:

- Total assets = sum of all assets
- Total liabilities = Sum of all liabilities
- Net Worth = Total assets - Total liabilities

I can see following fields please let me know which one are assets and which one are liabilities:
>> cash on hand, Checking accounts, Money market accounts, Credit cards, Home mortgages

And you want to calculate and update following fields whenever above fields changed:
>> Total Liabilities, Total Assets, Net Worth

Thank you

#568862

Hi Noman,

Assets - cash on hand, Checking accounts, Money market accounts i.e. Total Assets = cash on hand = Checking accounts = Money market accounts

Liabilities - Credit cards, Home mortgages I.e. Total Liabilities = Credit cards + Home mortgages

Net Worth = Total Assets - Total Liabilities

Yes, auto calculate when any change of asset or liability field - Total Liabilities, Total Assets, Net Worth

please note that this is the above is a simple version of the calculation I want to have. in reality I will have a long list of assets and a long list of liabilities.
not sure if there is a better way to identify a custom field as an asset or liability and then just sum them programmatically
for instance create only 2 custom fields one is 'Asset' and the other is 'Liability' how ever each one 'Allow multiple-instances of this field' and each instance have a description ,of the asset or the liability, as well as the numeric value.

Hope this helps.
thanks,

David

#569038

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Thanks for providing more details, I am working on this issue and will update you shortly with my findings.

Thank you for your patience.

#569081

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Hello David,

Its ready, you can check here: hidden link

Here is solution for your current setup

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 );

Thanks

#569365

Thanks Noman,
it seems that things are working ok however I need to know where did you put the PHP code?
I would like to update the function in it to reflect other custom fields I'm going to add and need to know where it location.
I normally use a function plugin to create a separate function.php page so I dont lode anything with updates...

Please advise,
thanks,

David

#569371

BTW I updated the theme to the latest version and I lost the calculations. I guess the above code was put under the theme function.php page.

I try to put the above code under my custom function.php page outside of the theme (you can find it here hidden link) but when I save it I get an error:
"This plugin has been deactivated because your changes resulted in a fatal error.
Parse error: syntax error, unexpected '    if' (T_STRING) in /var/www/vhosts/davidzohar.com/httpdocs/wp-content/plugins/functions.php on line 45"
at the moment I lost the calculation.

please advise,
thanks,

David

#569408

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Hello David,

I have added code in custom functions.php file
hidden link

And updated following post, it is working as expected.
hidden link

Thanks

#569848

Thanks Noman,

this is partially work.
allow me to explain.
I created a CRED form for the Net Worth Post type.
when I insert numbers into the form and submit it the initial calculation is not preformed. hence I get '0' for all calculated fields.
my expectation is that when I submit the from and its published automatically the fields will be calculated.
the behavior is different if I create the a new Net Worth Post by using the admin dashboard and creating the new Net Worth post and click the publish button.
my expectation is that if a user create or update the data using a cred form the calculated fields will be updated.

to create a new net worth I use the page (with the cred from in it) hidden link
the form is available here hidden link

Please advise,
thanks,

David

#569909

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

fields calculated.png

Hello David,

> When I insert numbers into the CRED add new post form and submit it the initial calculation is not performed and I got '0' for all calculated fields.

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. Please check here:
hidden link

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 );
	}
}

Thank you

#569991

Hi Noman,

This is great it works wonderfully. Thank you !!!

I have one last question around this topic and its related to the last code you provided:

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 );
    }
}

how is this code need to look like if I have a few custom post type that I need to calculate every time they are update? I see the line : 'if ($form_data['id']==1337)' as only applying the calculation to the specific custom post type.
what happen if I have a few forms that need calculation on using CRED form (new or edit)? how can I change the code to be with an 'OR' statement rather than "=="?

Thanks a lot for all your help,
David

#570021

Noman
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Hi,

>> What happen if I have a few forms that need calculation on using CRED form (new or edit)?
Flowing code:

if ($form_data['id']==1337) {
        calculate_fields( $post_id );
    }

Replaced with:

if ( $form_data['id'] == 1337 || $form_data['id'] == 1338 || $form_data['id'] == 1339 || $form_data['id'] == 1340 ) {
        	calculate_fields( $post_id );
}

==> In above code 1338, 1339, 1340 will be your new/edit cred form ids.
==> Please make sure to use one same Custom Field and assign it to your both CPTs. If new CPTs will have different Custom Field names then you need to update main function / code as well.

Thanks