I'm Using a (Gravity) Form to create Custom Posts 'Bedrijfsanalyses'. The Custom Post Type contains custom fields, created with Types. I want to calculate the average from certain custom fields, calculated from ALL Custom Post Types 'Bedrijfsanalyses that contain that certain custom field.
What I have found in the Forum is that this isn't possible with Views without some extra coding. I have to create a function and shortcode to do the job, but I didn't find how to do this. Could You please help me?
I assume your custom fields is created with Types, which is using slug "certain-custom-field", in database the meta-key is "wpcf-certain-custom-field"
Please try this:
1) add codes in your theme/functions.php
function my_average_func($atts, $content) {
extract(shortcode_atts(array(
'slug' => 'wpcf-certain-custom-field',
), $atts));
global $wpdb;
$res = $wpdb->get_var( "SELECT AVG(`meta_value`) FROM $wpdb->postmeta WHERE `meta_key` = '$slug'" );
return $res;
}
add_shortcode( 'my_average', 'my_average_func' );
2) put the shotcode into your content: [my_average]
Thanx for the code. I'll have to mannualy check the calculation, but so far so good. Still one more question: is there a way to use the shortcode for calculating averages of other custom fields too? I know I could use this code with another slug to calculate the average for another custom field and so on, but this seems a bit bloated. Is it possible to write a shortcode witch I could use for more than one custom field? I saw that somewhere on this forum, but i can't find it anymore.
I've checked the calculation. I have six custom posts, but the code calculates the average based on seven items. There's no custom post in the wast basked... What could go wrong here?
Thanx luoy, both issues are resolved now. Prior to this question I did some experimenting with the custom post types and made a normal post with all the custom field in it. That was the 7th post with all the empty values in it.