Skip Navigation

[Resolved] Nested view with conditional sums

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

Problem:
How to sum values of different Fields in a view, sam as when using the PHP operator

$value += $result

Solution:
functions.php:

global $total;
function add_total_shortcode($atts, $content = '') {
global $total;
 
$total += wpv_do_shortcode($content);
}
 
add_shortcode('add-to-total', 'add_total_shortcode');
 
function show_total_shortcode() {
global $total;
$totalNew = $total;
$total = 0;
return $totalNew;
}
 
add_shortcode('show-total', 'show_total_shortcode');

Register those ShortCodes in Views > Settings > Compatibility > 3rd Party ShortCodes

use the ShortCodes in a View as this:

<wpv-loop>
    [types field="your-numeric-field" output="raw"][/types]
    [add-to-total]
      [types field="your-numeric-field" output="raw"][/types]
    [/add-to-total]
</wpv-loop>
[show-total]

100% of people find this useful.

This support ticket is created 8 years, 3 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.

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)

Tagged: 

This topic contains 9 replies, has 2 voices.

Last updated by gavinS 8 years, 3 months ago.

Assisted by: Beda.

Author
Posts
#358791

I am trying to create quite a complicated nested view with calculations and I am very confused.

I have a type called 'Jobs' which has field called 'Start Date' and 'Potential Value'.

I would like to show 3 sums of 'Potential Values' for all 'Jobs' whose start date fall within this month, next month and the month after that. I would like to break this down by author and only show the sums for the authors that share the same location as the user.

So the end result should look something like this:

Adrian

This month Next Month 2 Months from now
100,000 150,0000 80,000

Julia

This month Next Month 2 Months from now
150,000 100,0000 90,000

Pippa

This month Next Month 2 Months from now
200,000 120,0000 50,000

Rafieq

This month Next Month 2 Months from now
250,000 150,0000 75,000

I don't even know where to begin. I have been looking around on the forum here, but haven't found anything that I understand. I was hoping there would be a shortcode for sums, similar to [wpv-found-count] but it seems not?

I do already have the following function, which should be useful?

function check_user_from_same_location($type, $object) {
if ( $type == 'users' ) {
if ( empty( $object) ) {
$return = 0;
} else {
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
$user_location = get_user_meta($user_id, 'wpcf-location', true);
switch ($user_location) {
case 1:
$return = 'Durban';
break;
case 2:
$return = 'Joburg';
break;
case 3:
$return = 'Cape Town';
break;
case 4:
$return = 'Pietermaritzburg';
break;
case 5:
$return = 'Head Office';
break;
}
}
}
return $return;
}

Thanks

Gavin

#358829

Hello Gavin

Toolset does not provide any calculation Systems or codes.

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.

If you tell me specifically what Custom Fields you want to sum up, when and where, I can help you with some example codes.

As example here you will see a simple Sum Up ShortCode for a Custom Field attached to a post type:
https://toolset.com/forums/topic/sum-of-fields-in-a-view-2/#post-358787

Please acknowledge that this requires pure Custom PHP code, which is above the scope of our Support, but I would be delighted to assist you with tips and suggestions, and if possible also help with the code.

Thank you

#359151

Hi Beda

Thanks for the help.

That code is pretty simple, and easy to understand.

However what I want to do is only sum the values for a specific month (such as this month), and per user. And I only want to display the users that have the same location (custom user field) as the logged in user (using the function created by Shekar above). This is what I've done so far, I've made a parent view for the users as follows:

Content selection: Users / Any role

Loop output:

[wpv-layout-start]
	[wpv-items-found]
	<!-- wpv-loop-start -->
		<wpv-loop>
          [wpv-conditional if="('[types usermeta="location"][/types]' eq check_user_from_same_location())"]
          <div class = "row"> <strong>[wpv-user field="display_name"]</strong></div><br>
          <div class = "row">
             <div class = "col-xs-4 col-md-2">
                 This Month:
               [wpv-view name="bm-this-month-total"]
            </div>
          </div>  
          [/wpv-conditional]
		</wpv-loop>
	<!-- wpv-loop-end -->
	[/wpv-items-found]
	[wpv-no-items-found]
		<strong>[wpml-string context="wpv-views"]No items found[/wpml-string]</strong>
	[/wpv-no-items-found]
[wpv-layout-end]

And then I've tried to create a child view as follows:
(I'm not sure if this is necessary if I use a function? This is what I did successfully for another nested view with a count of posts)

Content selection: Post Type / Jobs

Filters:
Select posts with the author set by the parent view
Select posts with custom field 'Start Date' is a number equal to THIS_MONTH()

Then I was hoping I could do something like this, but obviously my PHP skills aren't so great.. 🙂

[wpv-layout-start]
	[wpv-items-found]
     <?php $Total = 0 ?>
	<!-- wpv-loop-start -->
		<wpv-loop>
          <?php $Total += wpcf-potential-value ?>
         
	    </wpv-loop>
     <?php echo $Total ?>
	<!-- wpv-loop-end -->
	[/wpv-items-found]
	[wpv-no-items-found]
		<strong>[wpml-string context="wpv-views"]No items found[/wpml-string]</strong>
	[/wpv-no-items-found]
[wpv-layout-end]

Is it possible to do something like this inside the view, or do I need a function? I assume if I do need a function, then I need to pass some other parameters to the function, such as author and date? I would like to be able to make totals for this month, next month, and the following month, so probably need to send a parameter for which of these I am trying to calculate?

Any help would be highly appreciated, but I understand this might be outside the scope of your support.

Thanks

Gavin

#359179

It's not possible to use PHP in a HTML editor like the View Loop.

In PHP we will need a query that gets the Posts, it's fields and finally their values, so to sum them up and return or populate another Field with a Summed Value.

I will write a sample but it will require me some time, please await my reply tomorrow.

Thank you for you patience.

#359445

This is one possible solution:
https://toolset.com/forums/topic/calculating-types-custom-fields-and-display-in-html-container/#post-345125

Then this is a more customized version that could help you going in the correct direction:
https://toolset.com/forums/topic/how-to-get-sum-of-custom-field/
https://toolset.com/forums/topic/sum-of-fields/

A full PHP solution can be like this (note, you need to customize the get_posts() query to your needs)

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

This will work just fine if you enhance the Query to return only posts in with the required details as mentioned by you.

To use the += operator as in PHP, but in ShortCode version, there is a even better approach that you can use directly in the view
(that allows you to make the query with the View and just calculate with PHP)

global $total;
function add_total_shortcode($atts, $content = '') {
global $total;

$total += wpv_do_shortcode($content);
}

add_shortcode('add-to-total', 'add_total_shortcode');

function show_total_shortcode() {
global $total;
$totalNew = $total;
$total = 0;
return $totalNew;
}

add_shortcode('show-total', 'show_total_shortcode');

Register both shortcodes in Views (add-to-total and show-total)
Then use the ShortCode as this:

<wpv-loop>
    [types field="your-numeric-field" output="raw"][/types]
    [add-to-total]
      [types field="your-numeric-field" output="raw"][/types]
    [/add-to-total]
</wpv-loop>
[show-total]

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

Thank you for your patience.

#360434

Hi Beda

I tried the shortcode version, but it didn't seem to work?

Anyway, trying to understand how to write a function with query parameters. Something like this?


function calc_func( $atts ){
   
// get all jobs with author equal to shortcode parameter 'author'
        $all_posts = get_posts(array(
            'post_type'  => 'job',
            'author' => $atts['author'],                
		)
             );
   
//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 potential value
                $single_post_value = get_post_meta($single_post_id, 'wpcf-potential-value', true);
                                //get each posts start date
                $single_post_start_date = get_post_meta($single_post_id,'wpcf-start-date',true);

   
                //we need to sum this up BEFORE the if is closed and BEFORE the foreach is closed
                //Sum the values of posts with start date month == current month

                if(date('m', $single_post_start_date) == date('m')) {  
//is this the right way to reference the current month?
                           $single_posts_value_sum+= $single_post_value; 
                }
            }               
        }
return $single_posts_value_sum; //return summed value
}
   
add_shortcode( 'calc-total', 'calc_func' );

#360666

What do you mean with "didn't seem to work"?
Can you elaborate what the result was?

That ShortCode worked just fine locally.
Have you registered it in Views > Settings > 3rd Party ShortCodes?
Did you use a raw output of numerical Field?

That worked fine locally.

TO help you better with I now need access.
We deal with Custom code and non-default features of Toolset here and I can be of limited assistance only in this cases.
Our Company Policy does not allow the coding, provision and assistance with Custom Codes.

Nonetheless I want to know why on your end the code does not work.

I would need to request temporary access (WP-Admin and FTP) to your site
- preferably to a test site where the problem has been replicated if possible -
in order to be of better help and check if some configurations might need to be changed

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

❌ Please backup your database and website ❌

✙ I would, if possible, need access to a site where only a minimal set of Plugins and a default theme is active.
This to avoid eventual compatibility issues with other software.

✙ Please add the Links to:

- The Views Edit Screen

- The Page/Post where you insert the View

- The corresponding Front End Page/Screen

I need the exact instructions what fields have to be summed up, where they are stored, where I can see them.

I need to edit functions.php and the Views in regard.

Thank you

#360957

Yeah, but the "No Items found" is a issue of Query results, not of our ShortCode above.

As you correctly recognize, a Query Filter is somehow not matching your Content.

I will login and shortly see what the issue is.

Please expect my informations here in the forum.

Thank you for your patience.

#360970

So, there are some issues:

1. You did not follow the instructions as outlined here:
https://toolset.com/forums/topic/nested-view-with-conditional-sums/#post-359445

- Use the functions to register the ShortCodes
- Register the ShortCodes
- Use them as this exact example:

<wpv-loop>
    [types field="your-numeric-field" output="raw"][/types]
    [add-to-total]
      [types field="your-numeric-field" output="raw"][/types]
    [/add-to-total]
</wpv-loop>
[show-total]

==> You currently use:

<wpv-loop>
          [types field="potential-value" output="raw"][/types]
          [add-to-total]
         
	    </wpv-loop>
     [show-total]

That will not work, the shortCode is not adding anything, and it's not closed as well.
I don't see the ShortCode function in your Child's theme functions.php:
hidden link

It's the Child View that returns no results.
How do I know this?

I simply edit the "No Edits Found" string in both Views to something unique.

The Value that changes on the front end indicates me where the error relies (in which View)

So, I removed the Date Query, and my suspicions where confirmed:

1. The Short Code is not registered (the ShortCode just parses as bare text on the front end)
2. The Date Query is not matching content.

I was not able to test other filters, as I would suggest to filter a Date between 2 values (past and future month as example)
I was not able because the site took too long to reload simple Post Edit Screens or Front Page to compare the results.
I assume you have a shared server or a big load of queries running?

I deleted for now the Date query, as it makes it impossible for you to see the actual work of our shrotcode here.

If you can't get it to work with the date, please open a new ticket for that.

We also have a DOC about this:
https://toolset.com/documentation/user-guides/filtering-views-query-by-date/

Thank you

#361021

Oh gosh. Sorry man. I totally misread the bit on how to use the shortcode.

I did register the shortcodes, and they were in functions.php, but I must have had a couple of windows open and accidentally oversaved those functions at some point.

The problem was I hadn't closed the shortcode off with [/add-to-total]. For some reason I totally misread that as you trying to add two values to the total. I don't know why.

Thanks for all your help. It seems to be working now. Yay.

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