Skip Navigation

[Resolved] Sum of Custom fields calculation

This support ticket is created 4 years 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 1.07 hours from now. Thank you for your understanding.

Sun Mon Tue Wed Thu Fri Sat
- 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Kolkata (GMT+05:30)

This topic contains 8 replies, has 2 voices.

Last updated by connorR 4 years ago.

Assisted by: Minesh.

Author
Posts
#1558803

Tell us what you are trying to do?

I have a travel website I'm developing and for a cool feature I had in mind I wanted to dynamically have the sum of some custom fields be displayed. For example, I have a post that displays the price of a flight and a related post that has the price the airline charges for a checked bag and another related post that displays the price of a hotel. All these post relations I have no problem displaying on the front end with toolset views, but rather than having to go and add each time I thought it would be so convenient to have these dynamically calculated and displayed.

For example, I have my custom post type "flights" that I want this information displayed

the flight is $200

the related post of "airline" displays $30 as the checked bag price in a view

and another related post of hotel that displays $100 as the price, also in a view

in this case the total would be $330 and I would like to have that calculated and able to be displayed on that same page. Basically, this is just a simple addition calculation, but would be very useful and save me a ton of time in the long run

Is there any documentation that you are following?

I saw similar topics that needed to add to the functions.php file to create a shortcode

Is there a similar example that we can see?

None
What is the link to your site?

In development

#1559617

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

Hello. Thank you for contacting the Toolset support.

As I understand, you have related posts where you have another custom field that holds other price values and you want to add the current post price as well as related posts custom field values (price) and display it as a total? If this is correct - there is no native way to make total of the price other than we write a custom shortcode.

However - what if you add a new custom field namely "total price" and whenever a parent/related post get saved/updated you should update the total price field value - does that make sense?

#1560683

That is an option I thought about but, I am going to have hundreds if not thousands of posts so over time this would get very tedious and not to mention, the post type of "flight" has a price point that will be constantly updated and edited.

So for this, I think I would like to go the custom shortcode route. If you could give me some direction that would be very helpful, thanks!

#1561029

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

For custom code - you can use the post-relationship API function toolset_get_related_posts() to get the related posts:
=> https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/#toolset_get_related_posts

once you get the related posts, you should try to get the value of your custom fields and make a total and return the total value.

Please check the following doc that could help you to build shortcode:
=> https://toolset.com/documentation/adding-custom-code/how-to-create-a-custom-shortcode/

You can also use the Types PHP API function types_render_field() to get the custom field value:
=> https://toolset.com/documentation/customizing-sites-using-php/functions/

More info:
=> https://toolset.com/documentation/customizing-sites-using-php/

I hope the above information will help you to build your custom shortcode and display the total.

#1566455

Thank you for your support Minesh, I looked into the suggestions given but felt that it was quite a task for an essentially simple operation. Since the data I need for the calculation (prices) is already displayed on the page, the only operation I needed was to add them. Not sure why I didn't think of this, but I assigned an ID to the prices (text) and I just wrote a simple javascript operation that gets the text by element ID, converts it to an integer, then allows the simple equation to be calculated.

During my research, as in before I made this thread, I saw that there were several others that were interested in a similar feature. In my opinion, javascript is the best option, given that toolset can so easily can display text dynamically without the need of creating shortcodes etc.

Thanks for you help!

#1567485
Calculate average from custom field - Toolset 3-29-2020 7-57-45 PM.png

Rather than opening a new ticket, I have another question that falls in a very similar category.

In another CPT called "destinations" I have a related CPT "ratings" just for the purpose of letting users rate certain features of that destination, with numbers only on a 1-100 scale. This custom post type has a cred form which creates the one to many post relationship automatically.

So users submit this cred form which automatically creates a new ratings post. Let's say the destination is London, UK and the user submits their ratings, let's say 80, 90, 70, etc... I want to be able to display the average of those ratings on the front end.

Of course, I can easily display these all the ratings post and their numbers using views but I simply want just the average not all the different rating posts displayed.

I did find a similar topic (photo included) that provides a shortcode to display the average value of a particular field, the only problem is the same meta_key is used for the data that's saved to the database so by querying the average, the result is the average of all different destinations, not a particular one.

I'm just wondering if there would be a way to add to that shortcode to be able to filter it by wp_toolset_associations and the post id. That way I can just create a new shortcode each and manually add the post id of the destination I want displayed

#1567567

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

As you can see with the screenshot you shared - there is a custom query used to calculate the average rating.

To get related posts attached to specific Post ID - you can use the post-relationship API function: toolset_get_related_posts()
=> https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/#toolset_get_related_posts

For example:

$parent_id = 999;
$related_post_ids = toolset_get_related_posts(
                                    $parent_id,
                                    'clinic-location',
                                     'parent',
                                     1000,
                                      0,
                                      array(),
                                     'post_id',
                                     'child'
                                     );

Where;
- Replace 999 with your parent post ID
- Replace clinic-location with your post-relationship slug

You can adjust the code as required and adjust the custom query you shared in the screenshot.

Please let me know if you require further assistance with your issue.

#1568815

Took me many hours to get the final result, but you pointed me in the right direction. Very happy with the result, it works perfectly!

I was able to fine tune the code and added "get_the_ID()" to dynamically find the ID of the parent post, so I wont have to write a new function for each Destination post (I have hundreds so that would've been quite the hassle)

Here is the code I came up with in the end


function find_destination_child() {

    $parent_id = get_the_ID();
	$related_post_ids = toolset_get_related_posts(
										$parent_id,
										'destination-rating',
										 'parent',
										 1000,
										  0,
										  array(),
										 'post_id',
										 'child'
										 );		
	return $related_post_ids;			 								
}


function my_average_func($atts, $content) {
    extract(shortcode_atts(array(
		'slug' => 'wpcf-hotel-price'
		,
	), $atts));
	$childid = find_destination_child();
    global $wpdb;
    $res = $wpdb->get_var( "SELECT AVG(`meta_value`) FROM $wpdb->postmeta WHERE `post_id` IN (".implode(',',$childid).") AND `meta_key` = '$slug' " );
	
	return $res;
}
add_shortcode( 'my_average', 'my_average_func' );

Thanks again for steering me in the right direction!

#1570147

I have one last question, which may be too difficult to accomplish... Given that this ratings system I created works so well I wanted to see if it was possible to take these averages and update the parents fields with the averages.

For example, in my CPT Destinations, I have the same custom fields as I do for ratings. The ratings are from users and the the fields for destinations are manually entered by me. Because these are 2 separate CPT's when creating a view to display all destinations with sorting controls etc. of course I can only use these sorting controls from what's entered in the database, not by the calculated averages, even though those can be be displayed within the view with a shortcode.

Do you think there is any possible way I can create a function to automatically update a given "destination's" values in the database with the current calculated averages when someone submits a cred form for a new rating of that destination?

Or possibly sort by this calculated average within Toolset views custom searches?

Either that or another way would save me from having to manually go through and edit each destination to keep the ratings up to date and to properly correspond with the calculations

This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.