Skip to content

Instantly share code, notes, and snippets.

@xnau
Created March 31, 2024 07:04
Show Gist options
  • Save xnau/968581665cc406d68567ddf05e3834b8 to your computer and use it in GitHub Desktop.
Save xnau/968581665cc406d68567ddf05e3834b8 to your computer and use it in GitHub Desktop.
Shows how to create a custom format tag for a Participants Database calculated field
<?php
/**
* Plugin Name: PDB Age Detail Format Tag
* Description: shows how to add a custom formatting tag for use in a Participants Database calculated field
* Version: 1.0
*
*/
class PDb_age_detail_format_tag
{
/**
* sets up the filters
*/
public function __construct()
{
/*
* this is the name of the tag
* to use this in the calculated field, the tag will be: [?years_or_months]
*/
$tag = 'age_detail';
add_filter( 'pdb-calc_field_format_tag_' . $tag, array( $this, 'age_detail_tag' ), 10, 2 );
// use this if the tag is for display purposes only
add_filter( 'pdb-display_only_format_tag_' . $tag, function(){ return true; } );
}
/**
* provides the age_detail tag value
*
* @param string $value the raw result of the calculation (unix timestamp)
* @param \PDb_Field_Item $field the current field
* @return string
*/
public function age_detail_tag( $value, $field )
{
$interval = $this->interval_object( $value );
$format = [];
if ( $interval->format('%y') != 0 )
{
$format[] = '%y years';
}
if ( $interval->format('%m') != 0 )
{
$format[] = '%m months';
}
if ( $interval->format('%d') != 0 )
{
$format[] = '%d days';
}
// note: this won't be accurate to the day because it cannot account
// for the actual lengths of the months in the time span
return $interval->format( implode( ' ', $format ) );
}
/**
* provides the DateInterval object
*
* @param int $timestamp
* @return DateInterval object
*/
private function interval_object( $timestamp )
{
$y = $timestamp / YEAR_IN_SECONDS;
$years = intval( $y );
$m = ( $y - $years ) * 12;
$months = intval( $m );
$days = intval( ( $m - $months ) * 30.41 ); // 30.41 is the average month length in a year
$datecode = 'P' . $years . 'Y' . $months . 'M' . $days . 'D';
return new DateInterval( $datecode );
}
}
new PDb_age_detail_format_tag();
@xnau
Copy link
Author

xnau commented Mar 31, 2024

This article explains how to use this gist:

How to Install a WordPress Plugin from a Gist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment