Skip Navigation

[Resolved] Calculating aggregate data when view is filtered

This support ticket is created 3 years, 4 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
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: Africa/Casablanca (GMT+01:00)

This topic contains 10 replies, has 2 voices.

Last updated by garyN-2 3 years, 4 months ago.

Assisted by: Jamal.

Author
Posts
#2105789

Tell us what you are trying to do? I am trying to calculate aggregate data when a view is filtered. For instance getting the average rating of a restaurant as described here: https://toolset.com/forums/topic/how-to-get-rating-average-from-cred-for-review/
However, I want to be able to filter by the taxonomy: for instance Mexican. How do I reference the taxonomy selected in the search field in order to filter my query in the shortcode?
Is there any documentation that you are following. https://toolset.com/forums/topic/how-to-get-rating-average-from-cred-for-review/

Is there a similar example that we can see?

What is the link to your site?

#2105903

Hello and thank you for contacting Toolset support.

I am not sure to really understand your request. Can you elaborate more, or maybe provide more details about the current setup?

What I understood so far: You have a view of reviews, and you are currently calculating data using a custom shortcode. You would like to calculate the data per taxonomy term, for example, the aggregate data for reviews under the "Mexican" taxonomy term, right?
In that case, you can add a query filter to the view, so it does only return the posts/reviews that are under the "Mexican" taxonomy term.

Would you allow me temporary access to your website to check it closely? Your next reply will be private to let you share credentials safely. ** Make a database backup before sharing credentials. **

#2106433

Hello Gary,

Check this article about the WP_Query, you can see how the taxonomies can be included with the "tax_query" array.
https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters

For this case it should be this:

$args = array(  
    	'post_type' => 'ddq',
        'post_status' => 'publish',
      	'tax_query' => array(
        	array(
            	'taxonomy' => 'degree',
            	'field'    => 'slug',
            	'terms'    => 'chemistry',
        	),
    	),
    );

    $loop = new WP_Query( $args ); 

I updated the custom code and the shortcode seems to return the correct results. I'll let you test from your side and let me know if you still need assistance with it.

#2106735

Jamal,

This solution is hard coded to ‘chemistry’. I need to filter using the value in the search field at. hidden link.

#2106801

Sure. I just wanted to show how to include the taxonomy in the query.

Now, that you want to dynamically get it from the URL(generated by the search filter), you will need to check for the existence of it and if it actually holds a value that is different than 0, which stands for all the taxonomy terms:

    if ( isset( $_GET['wpv-degree'] ) && strlen( $_GET['wpv-degree'] ) > 0 && $_GET['wpv-degree']!= '0' ){

The code becomes:

  	$args = array(  
    	'post_type' => 'ddq',
        'post_status' => 'publish',
       // 'degree' => 'Chemistry',
    );
    if ( isset( $_GET['wpv-degree'] ) && strlen( $_GET['wpv-degree'] ) > 0 && $_GET['wpv-degree']!= '0' ){
      $args['tax_query'] = array(
        	array(
            	'taxonomy' => 'degree',
            	'field'    => 'slug',
            	'terms'    => $_GET['wpv-degree'],
        	),
    	);
    }

    $loop = new WP_Query( $args ); 
#2106839

Jamal,

I don't want to have to get from a url, I want to get from the search field. Is that possible?

#2106841

I realize I will have to use Ajax after the search field is changed.

#2106897

Well, using the current shortcode, there is no other way than from the URL, either with or without AJAX.

Otherwise, you need to loop through the results of the view and save the sum and the number of items in global variables until the last call when you display the results. Check an example that calculates the sum here https://toolset.com/forums/topic/how-to-aggregate-view-table-data/#post-286397

Please note that custom code is out of the scope of the support forum. We may provide some quick answers about it, but we won't invest too much time in it. Check our support policy https://toolset.com/toolset-support-policy/
If you are not comfortable with programming, you should hire a developer.

#2107021

Jamal,

Can I use the Search Form (Part of View) to set up the url? In other words, use the search form, user enters a taxonomy, create url based on entered taxonomy and call the url?

#2107529

Well, that's not really the question to ask. Because the view's filter enforces its own way of working. For views that do not use AJAX, the view's filter will build the URL parameter so the server can know what filters are used and what values are passed for them. When the view uses AJAX, the view's search form will use POST requests to pass the filters' values to the server, so it can generate the correct results.

The question to ask is how to know what filter is being used by the view, and what value is chosen for it?

The answer is somehow complex, because of how Views work. If the view does not use AJAX, then the answer is within the URL. And we can get it from the global $_GET array. When the view uses AJAX, the answer is within the global array $_POST.
That's how the HTTP protocol and PHP work. Read more about it in these articles:
- hidden link
- hidden link
- hidden link

This being said, if your question is to calculate the average for the results of the view, based on what category is used, either for the first load or while performing AJAX calls?
Then, the shortcode needs to detect if the view is filtering using the custom taxonomy, and what taxonomy term is chosen. This can be done with the following code:

	$term = "";
	if ( defined('DOING_AJAX') && DOING_AJAX ) {
		$search = isset( $_POST['search'] ) ? $_POST['search'] : array();
		$params = isset( $search['dps_general'] ) ? $search['dps_general'] : array();
		foreach( $params as $param ) {
			if ( $param['name'] == 'wpv-degree' ) {
				$term = $param['value'];
			}
		}
	} else {
		$term = isset( $_GET['wpv-degree'] ) ? $_GET['wpv-degree'] : "";
	}

Then, we should check if it is not the default value. In your case, it is the "all" value. Check this screenshot hidden link
That can be done with the following code:

if ( strlen( $term ) > 0 && $term != '0' ){

In that case, it means, that the user is actually filtering using a taxonomy term. And we should update our WP_Query arguments:

if ( strlen( $term ) > 0 && $term != '0' ){
  $args['tax_query'] = array(
        array(
            'taxonomy' => 'degree',
            'field'    => 'slug',
            'terms'    => $term,
        ),
    );
}

I tested the code and it works as expected. This is the final code:

add_shortcode('rating-average', 'rating_average_func');
function rating_average_func(){	
  	$args = array(  
    	'post_type' => 'ddq',
        'post_status' => 'publish',
       // 'degree' => 'Chemistry',
    );
	$term = "";
	if ( defined('DOING_AJAX') && DOING_AJAX ) {
		$search = isset( $_POST['search'] ) ? $_POST['search'] : array();
		$params = isset( $search['dps_general'] ) ? $search['dps_general'] : array();
		foreach( $params as $param ) {
			if ( $param['name'] == 'wpv-degree' ) {
				$term = $param['value'];
			}
		}
	} else {
		$term = isset( $_GET['wpv-degree'] ) ? $_GET['wpv-degree'] : "";
	}
  
  	if ( strlen( $term ) > 0 && $term != '0' ){
      $args['tax_query'] = array(
        array(
            'taxonomy' => 'degree',
            'field'    => 'slug',
            'terms'    => $term,
        ),
      );
	}

    $loop = new WP_Query( $args ); 
    $sum = 0;
    $num = 0;    
  	//var_dump($loop);
    while ( $loop->have_posts() ) : $loop->the_post(); 
        $sum=$sum + get_post_meta(get_the_id(),'wpcf-encourage', true);
        $num ++;     
    endwhile;
    wp_reset_postdata(); 
    if($num>0)
    {
        $res = $sum/$num;
    }
    return 'Average:'.$res;
}

Now, because you want to use AJAX for the view, you need to put the shortcode inside the view, but also outside the loop. Currently, it is outside of the view, so I drag/drop it inside the view's output, but outside the loop. Check this screenshot hidden link

#2107745

My issue is resolved now. Thank you!