Last active
July 24, 2024 21:34
-
-
Save hereswhatidid/8104f32029141147a867e606f914bd46 to your computer and use it in GitHub Desktop.
Create a custom Gravity Forms merge tag
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 | |
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(); |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And you did it good.