Hi! I'm building a peer-to-peer crowdfunding site, and I'd like to be able to display a total amount raised from all the donations to that campaign. There's a Campaign type, and a Donation type. Each Campaign can have multiple donations. How would I add up all of the donations of a single campaign to populate an 'Amount Raised' field in the campaign?
You could create a View to iterate over the child donations of the current campaign, adding a custom shortcode to handle the maths (there is no built-in calculation ability), but you would need to use the legacy Views builder and it involves writing custom code anyway, so you would probably be better off skipping that View and just writing the custom shortcode directly.
You would use the relationships API to get all of the child donation posts, do the calculation, and return the total.
Gotcha. So I'm using the are new API, but it's still returning an empty array. Anything I'm doing wrong here?
Thanks!
$children = toolset_get_related_posts(
// Post representing a writer (or post ID),
// to which the results should be related.
$campaignID,
// Relationship slug.
'campaign-donation',
// Additional arguments.
[
// Specify the role to query by and to return.
// Notice that we can use "other" in this situation.
'query_by_role' => 'child',
'role_to_return' => 'all',
// Ordering
'orderby' => 'llc-donation-amount',
'order' => 'ASC'
]
);
How do you setup the custom field "llc-donation-amount"? if it is created with Toolset Types plugin, you will add prefix "wpcf-" before the field slug, for exmaple "wpcf-llc-donation-amount"
Got it. By switching the 'role', I got results. Issue is now the loop isn't adding up the amount_raised field. Any thoughts? Thank you!!!!
$children = toolset_get_related_posts(
// Post representing a writer (or post ID),
// to which the results should be related.
$campaignID,
// Relationship slug.
'campaign-donation',
// Additional arguments.
[
// Specify the role to query by and to return.
// Notice that we can use "other" in this situation.
'query_by_role' => 'parent',
'role_to_return' => 'all'
]
);
$sum = 0;
foreach($children as $id){
$sum += get_post_meta( $id, 'wpcf-llc-donation-amount', true);
}
return $sum;
See the result you mentioned above:
["child"]=> int(129)
Number 129 is the child post ID, you can use it to get child post information, if you want to get custom field, you can try with WP function:
get_post_meta()