Skip to content

Instantly share code, notes, and snippets.

@spivurno
Last active May 31, 2019 15:52
Show Gist options
  • Save spivurno/45d589ad4b79ae88ad2ee0f695407ec3 to your computer and use it in GitHub Desktop.
Save spivurno/45d589ad4b79ae88ad2ee0f695407ec3 to your computer and use it in GitHub Desktop.
Gravity Wiz // Gravity Forms // Add Formatting Options for Date Merge Tags
<?php
/**
* Gravity Wiz // Gravity Forms // Add Formatting Options for Date Merge Tags
* http://gravitywiz.com/
*
* {Date:1:dmy} => 31/1/2017
* {Date:2:l} => Tuesday
*
* See PHP's date() function documentation for full details on formatting:
* http://php.net/manual/en/function.date.php
*/
add_filter( 'gform_pre_replace_merge_tags', function( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format ) {
preg_match_all( '/{[^{]*?:(\d+(\.\d+)?)(:(.*?))?}|{entry:date_created:(.+)?}/mi', $text, $matches, PREG_SET_ORDER );
foreach ( $matches as $match ) {
$input_id = $match[1];
$field = GFFormsModel::get_field( $form, $input_id );
$is_entry_date = strpos( $match[0], '{entry:date_created' ) !== false;
if( $is_entry_date ) {
$modifier = rgar( array_map( 'trim', explode( ',', rgar( $match, 5 ) ) ), 0 );
$value = rgar( $entry, 'date_created' );
} else if( ! $field || $field->get_input_type() != 'date' ) {
continue;
} else {
$i = $match[0][0] == '{' ? 4 : 5;
$modifier = rgar( array_map( 'trim', explode( ',', rgar( $match, $i ) ) ), 0 );
if( ! $modifier ) {
continue;
}
$value = GFFormsModel::get_lead_field_value( $entry, $field );
$value = $field->get_value_merge_tag( $value, $input_id, $entry, $form, $modifier, $value, $url_encode, $esc_html, $format, $nl2br );
}
$replace = date( $modifier, strtotime( $value ) );
$text = str_replace( $match[0], $replace, $text );
}
return $text;
}, 10, 7 );
@mkormendy
Copy link

@mkormendy
Copy link

mkormendy commented May 31, 2019

Loving me some of this. Question though: why are you array_mapping and exploding on commas? That inadvertently breaks the formatting if a person chooses to format their date to something readable like 'December 14, 2004'. In my case I replaced the comma with a section (§) in hopes that I never use section in a date format.

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