Skip to content

Instantly share code, notes, and snippets.

@xnau
Last active January 15, 2023 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xnau/afa89e8516e4b2c204d69bcaf7798876 to your computer and use it in GitHub Desktop.
Save xnau/afa89e8516e4b2c204d69bcaf7798876 to your computer and use it in GitHub Desktop.
Shows how to set up a custom calculation on a Participants Database Participant Log
<?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