Shows how to set up a custom calculation on a Participants Database Participant Log
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: PDB Custom Log Sum | |
* Description: calculates a summary value for a participant log | |
*/ | |
class pdb_custom_log_sum { | |
/** | |
* @var string the name of the log | |
*/ | |
private $logname = 'work_log'; | |
/** | |
* sets up the filter | |
*/ | |
public function __construct() | |
{ | |
// add the filter hander using the log's name for the filter, then link it to our method | |
add_filter( 'pdblog-' . $this->logname . '_sum', array( $this, 'get_sum' ), 10, 2 ); | |
} | |
/** | |
* provides the sum value | |
* | |
* @param int|float $sum the incoming sum value | |
* @param array $log_values array of log field values | |
* @return int|float the log sum | |
*/ | |
public function get_sum( $sum, $log_values ) | |
{ | |
return $this->calculate( $log_values ); | |
} | |
/** | |
* calculates the summary value | |
* | |
* @param array $log_values | |
* @return int|float summary value | |
*/ | |
private function calculate( $log_values ) | |
{ | |
// if there are no log entries, return a 0 | |
if ( ! is_array( $log_values ) || count( $log_values ) === 0 ) { | |
return 0; | |
} | |
/* | |
* the $log_values array is an array of data objects, | |
* one for each entry in the record's log | |
* | |
* we iterate over the array and collect the values | |
* we need to calculate the sum | |
*/ | |
$total_hours = 0; | |
foreach( $log_values as $entry ) | |
{ | |
// total up all the values in the "hours" field | |
$total_hours += $entry->hours; | |
} | |
// get the average number of hours per day the volunteer logged | |
$average = $total_hours / count($log_values); | |
return $average; | |
} | |
} | |
new pdb_custom_log_sum(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment