Skip to content

Instantly share code, notes, and snippets.

@thierrypigot
Last active August 29, 2015 14:25
Show Gist options
  • Save thierrypigot/8cfd0a6f56fcf7c2cdb6 to your computer and use it in GitHub Desktop.
Save thierrypigot/8cfd0a6f56fcf7c2cdb6 to your computer and use it in GitHub Desktop.
Permets de compter la valeur la plus sélectionnée dans un formulaire Gravity Forms
/**
* Exemple de formulaire
* Qx = Question
* - Réponse : valeur
*
**/
Q1 : Tu aimes quel animal ?
- Cheval : cheval
- Papillon : papillon
- Ours : ours
Q2 : Qui est le plus féroce ?
- Le papillon : papillon
- L'ours : ours
- Le cheval : cheval
Q3 : Ta soeur ressemble à :
- Un ours : ours
- Un cheval : cheval
- Un papillon : papillon
--------------------------------------------------------------------------------------
/**
* Texte à mettre dans le message de confirmation
**/
Bravo ! Voici ton animal secret :
[gravityforms action="conditional" merge_tag="{most_common}" condition="is" value="cheval"]Tu es un cheval[/gravityforms]
[gravityforms action="conditional" merge_tag="{most_common}" condition="is" value="papillon"]Tu es un papillon[/gravityforms]
[gravityforms action="conditional" merge_tag="{most_common}" condition="is" value="ours"]Tu es un ours !!!![/gravityforms]
<?php
/* Add {most_common} merge tag.
* For assigning a unique quiz result based on most common quiz answer (A, B, C, D, value) */
/**
* @param $merge_tags
* @param $form_id
* @param $fields
* @param $element_id
*
* @return array
*/
function tp_custom_merge_tags($merge_tags, $form_id, $fields, $element_id) {
$merge_tags[] = array('label' => 'Most Common Answer', 'tag' => '{most_common}');
return $merge_tags;
}
add_filter('gform_custom_merge_tags', 'tp_custom_merge_tags', 10, 4);
/* Replace merge tag with most common value */
/**
* @param $text
* @param $form
* @param $entry
* @param $url_encode
* @param $esc_html
* @param $nl2br
* @param $format
*
* @return mixed
*/
function tp_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) && trim( $val ) != '' ) {
$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;
}
add_filter('gform_replace_merge_tags', 'tp_replace_custom_merge', 10, 7);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment