billrobinson
Member
Posted 5 years ago #
I am using WP for a project log - each post has a custom field ('duration') to log an activity's duration in hours.
I would like to be able to sum these values to produce a cumulative total for project hours to date.
I am not familiar with PHP, nor with SQL, and so I hope someone can suggest the form which a query to do this would take, and whether (as I suspect) I will need to do a type conversion before summing the values?
billrobinson
Member
Posted 5 years ago #
I sorted it out myself - if anyone else is interested, code excerpt is below - probably not elegant, but hey... (the custom field I am using is called 'Duration')
$now = current_time('mysql');
$sql = "SELECT ";
$sql .= "meta_value FROM $wpdb->posts AS posts, $wpdb->postmeta AS postmeta ";
$sql .= "WHERE posts.ID = postmeta.post_id AND postmeta.meta_key = 'Duration' ";
$sql .= "AND ( posts.post_status = 'publish' ";
$sql .= " ) AND posts.post_date < '$now' ";
$sql .= "AND postmeta.meta_value != '' ";
$results = array(); $values = array();
$results = $wpdb->get_results($sql);
$totalDuration = 0;
if (!empty($results)){
foreach ($results as $result) {
$totalDuration += $result->meta_value;
}
}
echo $totalDuration.' hours';