Hi!
I have a custom post type: Volunteer
Volunteer has select custom field called Project
Volunteer has numeric custom field called Donations
I want to count the total sum of the Donations custom field based on the project and display it with a shortcode.
For example: [total_donations_sum project="Ethiopia-2019"]
This way I can display the total donation amounts Volunteers have received for each project.
I managed to create a function and shortcode that counts the sums of all the Donations custom fields from all the Volunteer post types using this:
https://toolset.com/forums/topic/how-to-get-sum-of-custom-field/
My current function is this:
function func_total_donations_sum( $atts ) {
global $wpdb;
if ((isset($atts['field'])) && (!empty($atts['field']))) {
$field=$atts['field'];
$post_table= $wpdb->prefix."posts";
$post_type='volunteer';
//Get all post IDS associated with the defined post type
$postid_array = $wpdb->get_results($wpdb->prepare("SELECT ID FROM $post_table WHERE post_type = %d AND post_status='publish'",$post_type), ARRAY_A);
//Clean IDs
$cleaned_id=clean_ids_func($postid_array);
$meta_value_array=array();
if (is_array($cleaned_id) && (!(empty($cleaned_id)))) {
//Loop through the post IDs and get their meta values
foreach ($cleaned_id as $k=>$v) {
$meta_value_post=get_post_meta($v,'wpcf-donations',TRUE);
if (!empty($meta_value_post)) {
$meta_value_array[]=$meta_value_post;
}
}
}
$sum=array_sum($meta_value_array);
return $sum;
}
}
function clean_ids_func($postid_array) {
if (!(empty($postid_array))) {
//Clean up
$clean_ids=array();
foreach ($postid_array as $k=>$v) {
if ((is_array($v)) && (!(empty($v)))) {
$clean_ids[]=reset($v);
}
}
if (!(empty($clean_ids))) {
return $clean_ids;
} else {
return FALSE;
}
} else {
return FALSE;
}
}
add_shortcode(' total_donations_sum',' func_total_donations_sum');
This shortcode counts ALL the Donations fields from ALL the Volunteer posts.
I need to limit the sum to Volunteers who are in a specific project.
I think other users and developers would like a solution like this in the future as well.
Can you help me?
Hi, I can show you how to use Views created a list of Volunteers filtered by Project. Then in your PHP code, you can use the Views API to get an array of all those Volunteer IDs. This will replace your $postid_array, and the rest of the code will stay the same.
- Create a View of Volunteers filtered by the project custom field, where the project field value is set by a shortcode attribute "project"
- The Loop output is not important
- Call the get_view_query_results API to retrieve an array of results:
$project = $atts['project'];
$postid_array = get_view_query_results( 12345, null, null, array( 'project' => $project ) );
Replace 12345 with the numeric ID of this View. More information about this API:
https://toolset.com/documentation/programmer-reference/views-api/#get_view_query_results