Skip to content

Instantly share code, notes, and snippets.

@hereswhatidid
Last active November 3, 2023 06:12
Show Gist options
  • Save hereswhatidid/8104f32029141147a867e606f914bd46 to your computer and use it in GitHub Desktop.
Save hereswhatidid/8104f32029141147a867e606f914bd46 to your computer and use it in GitHub Desktop.
Create a custom Gravity Forms merge tag
<?php
namespace HWID\SampleCode;
class GravityForms {
public static function init() {
add_filter( 'gform_custom_merge_tags', [ 'HWID\SampleCode\GravityForms', 'custom_merge_tags' ], 10, 4 );
add_filter( 'gform_replace_merge_tags', [ 'HWID\SampleCode\GravityForms', 'replace_merge_tags' ], 10, 3 );
}
/**
* Add custom merge tag to the merge tags drop down in the form editor
*
* @param array $merge_tags
* @param int $form_id
* @param array $fields
* @param int $element_id
*
* @return array
*/
static function custom_merge_tags( $merge_tags, $form_id, $fields, $element_id ) {
$merge_tags[] = array( 'label' => 'Name of Merge Tag', 'tag' => '{custom_merge_tag}' );
return $merge_tags;
}
/**
* Replace custom merge tags in field content if they are found
*
* @param string $text
* @param $form
* @param $entry
*
* @return string
*/
static function replace_merge_tags( $text, $form, $entry ) {
// Check to see if notification has the custom merge tag in it and replace it with the content of the tag
if ( strpos( $text, '{custom_merge_tag}' ) !== false ) {
$text = str_replace( '{custom_merge_tag}', 'Here it is!', $text );
}
return $text;
}
}
GravityForms::init();
@mklasen
Copy link

mklasen commented Apr 1, 2021

And you did it good.

@robertstaddon
Copy link

I had a problem with line 39 not evaluating to true if the string started with the merge tag. Replacing this line with "if ( strpos( $text, '{term_id}' ) !== false ) {" solved the issue for me.

@raftaar1191
Copy link

Useful @robertstaddon

It also fixed by issue

Thanks

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