WordPress > Getting Average Value of a Numerical Custom Field for Children of A Custom Post Type with a Given Post ID

The situation:

  • We have a custom post type, let’s call it: ‘cpt_parent’
  • We have another custom post type, which is a child of the aformentioned post type, let’s call it ‘cpt_child’
  • Our child custom post, ‘cpt_child’ has a custom field, let’s call it ‘cpt_child_numeric’
  • Our custom field ‘cpt_child_numeric’ holds only 1 value of 5 available values, 1, 2, 3, 5

What we want to do is get the average value of ‘cpt_child_numeric’ for a specific post_id of cpt_parent. For instance, say ‘cpt_parent’ has a post id of 33. For this id, we want to 1) count all child posts (cpt_child) 2) sum the value of ‘cpt_child_numeric’ for each ‘cpt_child’ post where the parent is ID 33 3) calculate the average.

Read More

What’s tripping us up is that we don’t want to do this within a loop, we want to be able to make the calculation by just having the parent post_id.

More than happy to clarify if need be

Thanks in advance!

Related posts

Leave a Reply

1 comment

  1. You can use wordpress custom query to get all these results like below:

    $postID = ”; // your parent post id

    1) For getting count of child posts

    $wpdb->get_results(" SELECT COUNT( columns_name ) FROM $wpdb->posts WHERE post_parent = $postID ");
    

    2) For getting sum of child posts

    $wpdb->get_results(" SELECT SUM( columns_name ) FROM $wpdb->posts WHERE post_parent = $postID ");
    

    3) For getting averageof child posts

    $wpdb->get_results(" SELECT AVG( columns_name ) FROM $wpdb->posts WHERE post_parent = $postID ");
    

    I hope this is what you want.
    Cheers!!!!