Hi there.
I have a parent post type called "Programs" with child post type called "Visits". In the child post type I have a numeric field called "total current hours".
Each parent post (Programs) will have 1 or more child posts (visits). How can I calculate the sum of all the child posts' "total current hours" fields and display the total on a CRED form for adding new "visits"?
Thanks!
To achive your need, please create the following custom code in your theme file functions.php.
/***
* Example shortcode: [get_sum parent_id='12']
*/
add_shortcode('get_sum', 'get_sum_func');
function get_sum_func( $atts ) {
/***
* Config your settings HERE
*/
$numeric_field = 'total-current-hours'; //change to your numeric field without 'wpcf-'
$parent_slug = 'program'; //change to your parent post slug (type)
$child_slug = 'visit'; //change to your child post slug (type)
extract( shortcode_atts( array(
'parent_id' => '', //Get the parent ID
), $atts ) );
$childargs = array(
'post_type' => $child_slug,
'numberposts' => -1,
'meta_key' => 'wpcf-' . $numeric_field,
'meta_query' => array(array('key' => '_wpcf_belongs_' . $parent_slug . '_id', 'value' => $parent_id))
);
$child_posts = get_posts($childargs);
$sum = 0;
foreach ($child_posts as $child_post) {
$sum += get_post_meta( $child_post->ID, 'wpcf-' . $numeric_field , true );
}
return $sum;
}
Then use the shortcode below in the place you want to display - change '12' to your parent post 'program' ID
Hi Dat. How can I make the shortcode ([get_sum parent_id='12']) automatically get the ID of the parent instead of me having to specify it each time?
Please use the following code. I modified it so that when there is no 'parent_id' in the shortcode, it will automatically look for the parent_id.
add_shortcode('get_sum', 'get_sum_func');
function get_sum_func( $atts ) {
/***
* Config your settings HERE
*/
$numeric_field = 'total-current-hours'; //change to your numeric field without 'wpcf-'
$parent_slug = 'program'; //change to your parent post slug (type)
$child_slug = 'visit'; //change to your child post slug (type)
extract( shortcode_atts( array(
'parent_id' => '', //Get the parent ID
), $atts ) );
if ( isset($_GET['parent_'.$parent_slug.'_id']) && $parent_id == '' ) {
$parent_id=intval($_GET['parent_'.$parent_slug.'_id']);
}
$childargs = array(
'post_type' => $child_slug,
'numberposts' => -1,
'meta_key' => 'wpcf-' . $numeric_field,
'meta_query' => array(array('key' => '_wpcf_belongs_' . $parent_slug . '_id', 'value' => $parent_id))
);
$child_posts = get_posts($childargs);
$sum = 0;
foreach ($child_posts as $child_post) {
$sum += get_post_meta( $child_post->ID, 'wpcf-' . $numeric_field , true );
}
return $sum;
}
Thanks Dat. This worked perfectly. I have another question for you. Is there a way for me to send you a private message?
Great to know that is working well for you.
Please open the new ticket and ask for the private reply 🙂