Skip Navigation

[Resolved] Build shortcode to calculate sum of child post custom post field

This support ticket is created 7 years, 2 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
- 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10: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: Asia/Kolkata (GMT+05:30)

This topic contains 2 replies, has 2 voices.

Last updated by romanB-3 7 years, 2 months ago.

Assisted by: Minesh.

Author
Posts
#566085

Hello,

I have a parent post type "PROJECT" with several children posts of post type "PRODUCT".

In PRODUCT post type, I have a custom field called "PRICE".

On a single PROJECT page, I need to calculate the sum of PRICES for children PRODUCTS of the actual PROJECT.

I assume I need to create a shortcode that would look like this :

function total_projet( $atts ) {
$totalprojet = 0;
// loop while current post has PRODUCT children
// $totalprojet = $totalprojet + get_post_meta($product_id, 'wpcf-total-ht', true);
// end loop
return $totalprojet;
}
add_shortcode('total-projet', 'total_projet');

Could you please help me getting the child post and build this function ?

Thank you very much.

#566314

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

Hello. Thank you for contacting the Toolset support.

To get the child posts of specific parent, you need to use the following code and loop through the $child_posts.

$childargs = array(
'post_type' => 'product',
'numberposts' => -1,
'meta_key' => 'wpcf-description',
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_query' => array(array('key' => '_wpcf_belongs_project_id', 'value' => YOUR-PARENT-POST-ID  ))
);
$child_posts = get_posts($childargs);

foreach($child_posts as $k=>$v):
    $totalprojet = $totalprojet + get_post_meta($v->ID, 'wpcf-total-ht', true);
endforeach;



Wheree:
=> Replace "YOUR-PARENT-POST-ID" with your parent post project ID.

More info:
=> https://toolset.com/documentation/user-guides/querying-and-displaying-child-posts/

#566389

Works great.
Thank you very much.