Skip Navigation

[Résolu] Sum of fields in a View

Ce fil est résolu. Voici une description du problème et la solution proposée.

Problem:
You have a Post type, and added to it a Custom Field (numeric) and want to display a sum of all those fields in a View.

Solution:

A example code, fully adapted for a query on WordPress default Post Type and a Custom Numeric Field called "numeric-one"

function calc_func( $atts ){
  
// get all Posts of your type
        $all_posts = get_posts(array(
            'numberposts'   => -1,
            'post_type'     => 'post',
            )
        );
  
//if it returns some posts
        if( $all_posts ){
 
            //Start the count on 0
        $single_posts_value_sum = 0;
 
            //now get the single posts fields values 
            foreach( $all_posts as $single_post ){ 
  
                //get each Posts post data
                $single_post_data = get_post($single_post);
                //get each ID
                $single_post_id = $single_post_data->ID;
                                //get each posts field value
                $single_post_value = get_post_meta($single_post_id, 'wpcf-numeric-one', true);
  
                //we need to sum this up BEFORE the if is closed and BEFORE the foreach is closed
                //Sum the values all posts fields
                $single_posts_value_sum+= $single_post_value; 
          
            }               
        }
return $single_posts_value_sum; //return summed value
}
  
add_shortcode( 'calc-total', 'calc_func' );

If you then use the ShortCode [calc-total] anywhere in your Site, you will see a total calculated from all fields "numeric-one" added to the Post Type "post"

100% of people find this useful.

This support ticket is created Il y a 8 années et 3 mois. 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.

No supporters are available to work today on Toolset forum. Feel free to create tickets and we will handle it as soon as we are online. Thank you for your understanding.

Sun Mon Tue Wed Thu Fri Sat
- - 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00
- - - - - - -

Supporter timezone: Asia/Ho_Chi_Minh (GMT+07:00)

Marqué : 

This topic contains 10 réponses, has 5 voix.

Last updated by Alan Il y a 8 années et 3 mois.

Assisted by: Beda.

Auteur
Publications
#358215

I am following up on a topic posted by kendrewP: https://toolset.com/forums/topic/sum-of-fields-in-a-view/

I am also trying to sum the iterations of specific numeric fields within a view. I'm displaying several fields in a table of results and the want a field under it with sum of field column: 'match-amount'

I have added the function count_numeric_custom_field_func and the shortcode suggested by Adriano to my theme functions.php file and then called the shortcode in my view like this:
[count_numeric_custom_field field="match-amount"]

The output returned is blank, when i tried to output the $regs, the result comes Array()

Could you please help me with this?

#358293

This is most probably because you followed the first Code suggestion there.
Adriano provided a fix for the exact problem you mention here:
https://toolset.com/forums/topic/sum-of-fields-in-a-view/#post-213825

Also please acknowledge that this code, calculates the Sum of ALL fields.

As you can see, the query of Adriano's code will SUM all values of all custom fields, not only the one listed in the view.

You can only use this code, if your view will list all posts in the same page, it's not possible to get a SUM only of the displayed posts custom fields.

It seems -unfortunately- that for now you need custom programming work which is beyond the scope of our support.

At this point I would suggest you consider contacting one of our certified partners from this link:
https://toolset.com/consultant/

You will get the custom assistance you need to get on with your project.

Please do not hesitate to open a new thread if other issues or problems arise

Thank you for your patience.

#358355
2016-01-11_0312.png
2016-01-11_0311.png

Hi,

I tried the same code, and it is not showing sum of all the custom fields.

Could you please check it again?

Here is my view code:

<td>[wpv-post-date format="F j, Y g:i a"]</td>
<td>[wpv-post-link]</td>
<td>[types field="match-number"][/types]</td>
<td>[types field="amount"][/types]</td>

Total: [count_numeric_custom_field field="amount"]

Output is blank, please see attachment.

Look forward to hearing from you.

Thanks

#358432

Let's try a different approach.

I understand you have a Post type, and added to it a Custom Field (numeric) and want to display a sum of all those fields in a View

In my opinion it's easier to to with a Query and then sum up via PHP the single values, return the sum in your shortcode and use that in your View or wherever you want.

So that would look like this:

function calc_func( $atts ){

// get all Posts of your type
		$all_posts = get_posts(array(
			'numberposts'	=> -1,
			'post_type'		=> 'your_post_type',
		);

//if it returns some posts
		if( $all_posts ){

			//now get the single posts fields values 
			foreach( $all_posts as $single_post ){ 

				//get each Posts post data
				$single_post_data = get_post($single_post);
				//get each ID
				$single_post_id = $single_post_data->ID;
                                //get each posts field value
				$single_post_value = get_post_meta($single_post_id, 'wpcf-your-field', true);

	           	//we need to sum this up BEFORE the if is closed and BEFORE the foreach is closed
	           	//Sum the values all posts fields
	           	$single_posts_value_sum+= $single_post_value; 
		
            }				
    	}
return $single_posts_value_sum; //return summed value

add_shortcode( 'calc-total', 'calc_func' );

You can then use the shortcode [calc-total]

As Views does not support any form of calculation it seems -unfortunately- that for now you need custom programming work which is beyond the scope of our support.

At this point I would suggest you consider contacting one of our certified partners from this link:
https://toolset.com/consultant/

You will get the custom assistance you need to get on with your project.

Please do not hesitate to open a new thread if other issues or problems arise

Thank you for your patience.

#358672

Hi,

Thank you for getting back to me.

Seems some issue with the code, as it breaks my site.

Look forward to hearing from you.

Thanks

#358787

As I mentioned, this is custom code and my above snippet is just a example.

I apologize that I made a typo:
I missed 2 closing Brackets, one for the get_posts and one to close the entire function itself.

Below code wont break your site:

function calc_func( $atts ){
 
// get all Posts of your type
        $all_posts = get_posts(array(
            'numberposts'   => -1,
            'post_type'     => 'your_post_type',
            )
        );
 
//if it returns some posts
        if( $all_posts ){
 
            //now get the single posts fields values 
            foreach( $all_posts as $single_post ){ 
 
                //get each Posts post data
                $single_post_data = get_post($single_post);
                //get each ID
                $single_post_id = $single_post_data->ID;
                                //get each posts field value
                $single_post_value = get_post_meta($single_post_id, 'wpcf-your-field', true);
 
                //we need to sum this up BEFORE the if is closed and BEFORE the foreach is closed
                //Sum the values all posts fields
                $single_posts_value_sum+= $single_post_value; 
         
            }               
        }
return $single_posts_value_sum; //return summed value
}
 
add_shortcode( 'calc-total', 'calc_func' );

Pleas always enable WP Debug Mode when you apply custom code, this helps to spot such typos quickly:
https://codex.wordpress.org/Debugging_in_WordPress

You will need to adapt this code, as I don't know the name of your Custom Fields and Posts.
You will also need to start your count before you get the Posts Query results to avoid undefined $variables.

That makes my code above looking like the below, fully adapted for a query on WordPress default Post Type and a Custom Numeric Field called "numeric-one"

function calc_func( $atts ){
 
// get all Posts of your type
        $all_posts = get_posts(array(
            'numberposts'   => -1,
            'post_type'     => 'post',
            )
        );
 
//if it returns some posts
        if( $all_posts ){

            //Start the count on 0
 	    $single_posts_value_sum = 0;

            //now get the single posts fields values 
            foreach( $all_posts as $single_post ){ 
 
                //get each Posts post data
                $single_post_data = get_post($single_post);
                //get each ID
                $single_post_id = $single_post_data->ID;
                                //get each posts field value
                $single_post_value = get_post_meta($single_post_id, 'wpcf-numeric-one', true);
 
                //we need to sum this up BEFORE the if is closed and BEFORE the foreach is closed
                //Sum the values all posts fields
                $single_posts_value_sum+= $single_post_value; 
         
            }               
        }
return $single_posts_value_sum; //return summed value
}
 
add_shortcode( 'calc-total', 'calc_func' );

If you then use the ShortCode [calc-total] anywhere in your Site, you will see a total calculated from all fields "numeric-one" added to the Post Type "post"

Please do not hesitate to open a new thread if other issues or problems arise

Thank you for your patience.

#361412

Worked like a charm, thank you so much 🙂

#904413

How Can I add one more step to this I would like to add IF account status = Not paid then add it up. and only if its NOT Paid here is my code that I added

function calc_func( $atts ){
   
// get all Posts of your type
        $all_posts = get_posts(array(
            'numberposts'   => -1,
            'post_type'     => 'invoice',
            )
        );
   
//if it returns some posts
        if( $all_posts ){
  
            //Start the count on 0
        $single_posts_value_sum = 0;
  
            //now get the single posts fields values 
            foreach( $all_posts as $single_post ){ 
   
                //get each Posts post data
                $single_post_data = get_post($single_post);
                //get each ID
                $single_post_id = $single_post_data->ID;
                                //get each posts field value
				$status = get_post_meta($single_post_id, 'wpcf-fc-account-status', true);
				$single_post_value = get_post_meta($single_post_id, 'wpcf-invoice-amount', true);
                //we need to sum this up BEFORE the if is closed and BEFORE the foreach is closed
                //Sum the values all posts fields
				if ( $status = 'Not Paid' ) {
				$single_posts_value_sum+= $single_post_value; 
				}
                
           
            }               
        }
	$getnumber =  $single_posts_value_sum; //return summed value
	setlocale(LC_MONETARY, 'en_US');
	$number = money_format('%(#10n', $getnumber) . "\n";
	return $number;
}
   
add_shortcode( 'calc-total', 'calc_func' );
#904416

Nevermind I was able to get it by reversing the if statement.

if (  'Not Paid' = $status ) {
#1105629

I am using this (below) - It works great - just need to know how to fire this on more than just products post type:

add_filter( 'wpv_filter_query_post_process', 'get_filtered_post_ids_from_view_for_summing', 10, 3 );

function count_numeric_custom_field_func( $atts ) {

if ((isset($atts['field'])) && (!empty($atts['field']))) {

$field=$atts['field'];

//Get all filtered post IDs from Views for summing
global $filtered_postid_for_summing;

$meta_value_array=array();

if ((isset($filtered_postid_for_summing)) && (is_array($filtered_postid_for_summing))) {

//Loop through the post IDs and get their meta values

foreach ($filtered_postid_for_summing as $k=>$v) {

$meta_value_post=get_post_meta($v,$field,TRUE);
if (!empty($meta_value_post)) {
$meta_value_array[]=$meta_value_post;
}
}
}
$sum=array_sum($meta_value_array);
return $sum;
}

}

add_shortcode('display_count_test','count_numeric_custom_field_func');

//Get posts displayed in filtered View
add_filter( 'wpv_filter_query_post_process', 'get_filtered_post_ids_from_view_for_summing', 10, 3 );

function get_filtered_post_ids_from_view_for_summing( $query, $view_settings, $view_id ) {

$post_type='products';

if (isset($query->posts)) {
if (!(empty($query->posts))) {
$filtered_posts=$query->posts;
if ((is_array($filtered_posts)) && (!empty($filtered_posts))) {
global $filtered_postid_for_summing;
$filtered_postid_for_summing=array();
foreach ($filtered_posts as $k=>$the_post) {
if ((isset($the_post->ID)) && ($the_post->post_type == $post_type)) {
$filtered_postid_for_summing[]=$the_post->ID;
}
}
}
}
}

return $query;
}

#1196386

This got me nearly all the way there. (Thanks)

I applied this and it is calculating and displaying a total for ALL posts (rather than filtered to the current view conditions).
Is there something I am missing.

CPT entry
CF number

I am looking for the shortcode to return a sum (total) of values only within the currently filtered view.

therefore

Posts (entry)

entry 1 > number = "1" (tagged "calc")
entry 2 > number = "2" (tagged "calc")
entry 3 > number = "3"

View filtered to display only items tagged "calc"

entry 1 > number = "1" (tagged "calc")
entry 2 > number = "2" (tagged "calc")

Shortcode to return "3"
(sum of entry 1 - number 1 and entry 2 - number 2 )

Appreciate the last yard help:)

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