Skip to content

Instantly share code, notes, and snippets.

@aliciaduffy
Last active August 29, 2015 14:00
Show Gist options
  • Save aliciaduffy/28e9f84b4dcba6243563 to your computer and use it in GitHub Desktop.
Save aliciaduffy/28e9f84b4dcba6243563 to your computer and use it in GitHub Desktop.
Most Common Value/Answer - Gravity Forms Merge Tag
<?php
/* Add {most_common} merge tag.
* For assigning a unique quiz result based on most common quiz answer (A, B, C, D, value) */
add_filter('gform_custom_merge_tags', 'custom_merge_tags', 10, 4);
function custom_merge_tags($merge_tags, $form_id, $fields, $element_id) {
$merge_tags[] = array('label' => 'Most Common Answer', 'tag' => '{most_common}');
return $merge_tags;
}
/* Replace merge tag with most common value */
add_filter('gform_replace_merge_tags', 'replace_custom_merge', 10, 7);
function replace_custom_merge($text, $form, $entry, $url_encode, $esc_html, $nl2br, $format) {
$custom_merge_tag = '{most_common}';
if(strpos($text, $custom_merge_tag) === false)
return $text;
$field_values = array();
foreach ($entry as $key => $val) {
// if key is num we are dealing with a field value
if ( is_int($key) ) {
$field_values[] = $val;
}
}
$count = array_count_values($field_values);
$most_common = array_search(max($count), $count);
// Take the most common value and replace {most_common} merge tag
$text = str_replace($custom_merge_tag, $most_common, $text);
return $text;
}
[gravityforms action="conditional" merge_tag="{most_common}" condition="is" value="pony"]
You are a pony.
[/gravityforms]
[gravityforms action="conditional" merge_tag="{most_common}" condition="is" value="starfish"]
You are a starfish.
[/gravityforms]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment