Last active
October 21, 2020 17:51
-
-
Save spivurno/9db18385ed1d1f11a897bdfa8a1f2007 to your computer and use it in GitHub Desktop.
Gravity Wiz // Gravity Forms // Advanced Conditional Shortcodes
This file contains hidden or 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 | |
/** | |
* Gravity Wiz // Gravity Forms // Advanced Conditional Shortcodes | |
* | |
* [gravityforms action="conditional" relation="any" | |
value="{:2}" operator="is" compare="First Choice" | |
value2="{:1}" operator2="isnot" compare2="Second Choice"] | |
Content you would like to conditionally display. | |
[/gravityforms] | |
* | |
*/ | |
add_filter( 'gform_shortcode_conditional', function( $result, $atts, $content ) { | |
if( ! isset( $atts['value'] ) || isset( $atts['merge_tag'] ) ) { | |
return $result; | |
} | |
$relation = strtolower( rgar( $atts, 'relation', 'all' ) ); // or 'any' | |
$conditions = array(); | |
foreach( $atts as $key => $prop ) { | |
preg_match( '|value(\d*)$|', $key, $match ); | |
if( ! empty( $match ) ) { | |
list( , $index ) = $match; | |
$conditions[] = array( | |
'value' => rgar( $atts, sprintf( 'value%s', $index ) ), | |
'operator' => rgar( $atts, sprintf( 'operator%s', $index ) ), | |
'compare' => rgar( $atts, sprintf( 'compare%s', $index ) ), | |
); | |
} | |
} | |
$conditional_met = $relation == 'all'; | |
foreach( $conditions as $condition ) { | |
$is_match = GFFormsModel::matches_operation( $condition['value'], $condition['compare'], $condition['operator'] ); | |
if( $relation == 'any' && $is_match ) { | |
$conditional_met = true; | |
break; | |
} else if( $relation == 'all' && ! $is_match ) { | |
$conditional_met = false; | |
} | |
} | |
if( ! $conditional_met ) { | |
return ''; | |
} | |
// find and remove any starting/closing <br> tags | |
if( rgar( $atts, 'format' ) != 'raw' ) { | |
$content = preg_replace( '/^<br(?: *\/)?>|<br(?: *\/)?>$/', '', $content ); | |
} | |
return do_shortcode( $content ); | |
}, 10, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is this code still relevant because this does not work
[gravityforms action="conditional" relation="any" value="{:9.1:label}" operator="is" compare="elektriciteit" value2="{:22.1:label}" operator2="is" compare2="gas"] (<b>{:9.1:label} en {:22.1:label}</b>) [/gravityforms]