Skip Navigation

[Resolved] Calculating the sum of custom field values across multiple Child posts

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

Problem:
I have to CPTs: Voyage and Ticket
Ticket CPT is a Child of Voyage CPT
Ticket CPT has a field titled total-tickets-available

A Voyage has 4 Child Tickets:
Ticket A total-tickets-available value is 5
Ticket B total-tickets-available value is 10
Ticket C total-tickets-available value is 2
Ticket D total-tickets-available value is 2

What I need to do is summarise these values and display the total (which would be 19 in this example) in the Parent Voyage.

Solution:
There ins't such kind of feature within Views plugin, Views is for displaying data, it can not calculate data, so in your case it needs custom codes, here is a example with detail steps:
1) create a custom shortcode to display the sum value, modify your PHP codes as below:

add_shortcode('sum-of-tickets-available', 'sum_of_tickets_available_func');
function sum_of_tickets_available_func(){
    $voyage_id = get_the_ID(); 
    $children = get_posts(
        array(
            'post_type'=> $child_slug,
            'meta_query' => array(
                array(
                    'key'     => '_wpcf_belongs_voyage_id',
                    'value'   => $voyage_id,
                ),
            ),
            'fields' => 'ids'
        )
    );
    $sum = 0;
    foreach($children as $id){
        $sum += get_post_meta( $id, 'wpcf-total-tickets-available', true);
    }
    return $sum;
}

2) Then in a single "Voyage" post, display the total value with shortcode:
[sum-of-tickets-available]

Relevant Documentation:
https://codex.wordpress.org/Function_Reference/get_posts

This support ticket is created 7 years, 1 month 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.27 hours from now. Thank you for your understanding.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9: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/Hong_Kong (GMT+08:00)

This topic contains 3 replies, has 2 voices.

Last updated by Luo Yang 7 years, 1 month ago.

Assisted by: Luo Yang.

Author
Posts
#580257

I have to CPTs: Voyage and Ticket
Ticket CPT is a Child of Voyage CPT
Ticket CPT has a field titled total-tickets-available

A Voyage has 4 Child Tickets:
Ticket A total-tickets-available value is 5
Ticket B total-tickets-available value is 10
Ticket C total-tickets-available value is 2
Ticket D total-tickets-available value is 2

What I need to do is summarise these values and display the total (which would be 19 in this example) in the Parent Voyage.

I have created a View with the below code...

[hide-it][wpv-layout-start][/hide-it]
	[wpv-items-found]
	<!-- wpv-loop-start -->
    <wpv-loop>[wpv-item index=1][types field='total-tickets-available' output='raw'][/types][wpv-item index=other], [types field='total-tickets-available' output='raw'][/types]</wpv-loop>
	<!-- wpv-loop-end -->
	[/wpv-items-found]
[hide-it][wpv-layout-end][/hide-it]

Then rendered this view and attempted to use the result in a calculation...

add_shortcode('sum-of-tickets-available', 'sum_of_tickets_available_func');
function sum_of_tickets_available_func(){

	$args = array(
 	   'id' => '434',
	);
	$results = render_view( $args ); 

	var x = calctickets($results);        // Function is called, view output will end up in x

	function calctickets(a, b) {
 	   return a + b;                // Function returns the sum of a and b
	}

}

Without the calculation I was able to render the view successfully using [sum-of-tickets-available], but with the calculation added in the site does not display, which means there's an issue in the php somewhere.

Given the above, can you let me know if this is the best approach to get the Total of the field values displayed, and if so, if you know what the error may be in the code I've written?

Though I'm no expert, I assume it's either the placement of the $args and $results and/or the fact that (a, b) may need adjusting depending on how many results there are being output.

Any advise would be most appreciated!

#580474

Dear Jon,

There ins't such kind of feature within Views plugin, Views is for displaying data, it can not calculate data, so in your case it needs custom codes, here is a example with detail steps:
1) create a custom shortcode to display the sum value, modify your PHP codes as below:

add_shortcode('sum-of-tickets-available', 'sum_of_tickets_available_func');
function sum_of_tickets_available_func(){
	$voyage_id = get_the_ID(); 
    $children = get_posts(
        array(
            'post_type'=> $child_slug,
            'meta_query' => array(
                array(
                    'key'     => '_wpcf_belongs_voyage_id',
                    'value'   => $voyage_id,
                ),
            ),
            'fields' => 'ids'
        )
    );
    $sum = 0;
    foreach($children as $id){
        $sum += get_post_meta( $id, 'wpcf-total-tickets-available', true);
    }
	return $sum;
}

2) Then in a single "Voyage" post, display the total value with shortcode:
[sum-of-tickets-available]

#581058

I have now tested this and got it working with just one change (for post_type I took away the $ and added the slug in single quotes as 'ticket').

Thanks for your help in achieving this!

For reference, the final code is below...

// Calculate Sum of Tickets Available for a Parent Voyage
add_shortcode('sum-of-tickets-available', 'sum_of_tickets_available_func');
function sum_of_tickets_available_func(){
    $voyage_id = get_the_ID(); 
    $children = get_posts(
        array(
            'post_type'=> 'ticket',
            'meta_query' => array(
                array(
                    'key'     => '_wpcf_belongs_voyage_id',
                    'value'   => $voyage_id,
                ),
            ),
            'fields' => 'ids'
        )
    );
    $sum = 0;
    foreach($children as $id){
        $sum += get_post_meta( $id, 'wpcf-total-tickets-available', true);
    }
    return $sum;
}
#581343

You are welcome