Last active
February 28, 2022 18:41
-
-
Save xnau/9bc6bfa1046e0f2927d25a10ce185ed6 to your computer and use it in GitHub Desktop.
Shows how to set up a custom calculation for a Participants Database calculated field
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 Calculated Field | |
* Description: demonstrates how to implement a custom calculation for a calculated field | |
*/ | |
add_filter( 'pdb-calculated_field_calc_value', 'pdb_calculate_value', 10, 3 ); | |
/** | |
* supplies the calculated value | |
* | |
* @param bool $result | |
* @param array $replacement_data values for the fields named in the calculation template | |
* @param \PDb_Field_Item $field the current field | |
* @return mixed bool false to use built-in calculation or the result of the calculation | |
*/ | |
function pdb_calculate_value( $result, $replacement_data, $field ) | |
{ | |
/* this is the field that we will be calculating the value for | |
* | |
* this must be the name of a Numeric Calculation or Date Caclculation field | |
* | |
*/ | |
$field_name = 'totals'; | |
if ( $field->name() === $field_name ) { | |
$record_data = Participants_Db::get_participant( $field->record_id ); | |
// shows a way to convert a text value to a number | |
$value_1 = $record_data['automobiles'] === 'local' ? 1 : 2; | |
// this value is set to 0 if it is empty to make sure the value is a number | |
$value_2 = empty( $replacement_data['distance'] ) ? 0 : $record_data['distance']; | |
$result = $value_1 * $value_2; | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you are using this to calculate a value based on other calculated field results, those other fields must be calculated first. You can set that up by changing the order of the fields on the Manage Database Fields page. Fields are calculated from top to bottom sequentially.
The result of the prior calculations will be in $replacement_data