Default Choice Merge Tags to Values

Forces choice-based merge tags to return values unless a modifier is already set.

Instructions

See “Where do I put snippets?” in our documentation for installation instructions.

Code

Filename: gw-default-choice-merge-tags-values.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
/**
 * Gravity Wiz // Gravity Forms // Default Choice Merge Tags to Values
 * https://gravitywiz.com
 *
 * Forces choice-based merge tags to return values unless a modifier is already set.
 */
add_filter( 'gform_pre_replace_merge_tags', function ( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format ) {

	// Set specific form IDs to target, or leave empty for all forms.
	$target_form_ids = array(); // e.g. array( 1, 3, 5 )

	if ( $target_form_ids && ! in_array( (int) rgar( $form, 'id' ), $target_form_ids, true ) ) {
		return $text;
	}

	preg_match_all( '/{[^{}]*?:(\d+(?:\.\d+)?)(?::([^}]*))?}/', $text, $matches, PREG_SET_ORDER );

	foreach ( $matches as $match ) {
		$field_id = $match[1];
		$field    = GFAPI::get_field( $form, $field_id );

		if ( ! $field || ! in_array( $field->get_input_type(), array( 'select', 'radio', 'checkbox', 'multiselect', 'option', 'product', 'poll', 'survey', 'quiz', 'post_category' ), true ) ) {
			continue;
		}

		$modifiers = isset( $match[2] ) && $match[2] !== '' ? array_map( 'trim', array_map( 'strtolower', explode( ',', $match[2] ) ) ) : array();

		// If any modifier is already present, honor it.
		if ( $modifiers ) {
			continue;
		}

		$replacement = rtrim( $match[0], '}' ) . ( $match[2] === '' ? ':value}' : ',value}' );
		$text        = str_replace( $match[0], $replacement, $text );
	}

	return $text;
}, 9, 7 );

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Trouble installing this snippet? See our troubleshooting tips.
  • Need to include code? Create a gist and link to it in your comment.
  • Reporting a bug? Provide a URL where this issue can be recreated.

By commenting, I understand that I may receive emails related to Gravity Wiz and can unsubscribe at any time.