Sometimes you want to determine if one or more specific checkboxes is checked, using a conditional. This is difficult because checkboxes group custom fields store data in a serialized array rather than raw data. In this example, we have a checkboxes group field “my-checkboxes” with 12 different options. The value of each option is an integer 1 – 12. If option 1, 2, 3, or 4 is checked, we want to display CRED form 1. If option 5, 6, 7, or 8 is checked, we want to display CRED form 2. If option 9, 10, 11, or 12 is checked, we want to display CRED form 3.
Add the following code to your child theme’s functions.php file to create a custom shortcode checkboxes_contain_any:
/* --------------------------------------------------------------------------------------- */ // ARE ANY OF THESE CHECKBOXES CHECKED? RETURN BOOLEAN FOR CONDITIONAL // Pass in a comma-sep string "any" to test against a comma-sep string of "test" values // Returns: boolean function checkboxes_contain_any_func($atts) { $a = shortcode_atts( array( 'any' => '', 'test' => '' ), $atts ); $any = isset( $a['any'] ) ? explode(',', $a['any']) : null; $test = isset( $a['test'] ) ? explode( ',', $a['test'] ) : null; return !empty( array_intersect( $any, $test ) ); } add_shortcode("checkboxes_contain_any", "checkboxes_contain_any_func");
You must add checkboxes_contain_any to Third Party Shortcode Arguments in Toolset > Settings > Frontend Content to allow this custom shortcode in a conditional. Putting it all together with three conditionals – one for each form:
[wpv-conditional if="( [checkboxes_contain_any any='[types field='my-checkboxes' separator=','][/types]' test='1,2,3,4'] eq '1' )"] [cred form="Cred form 1"] [/wpv-conditional] [wpv-conditional if="( [checkboxes_contain_any any='[types field='my-checkboxes' separator=','][/types]' test='5,6,7,8'] eq '1' )"] [cred form="Cred form 2"] [/wpv-conditional] [wpv-conditional if="( [checkboxes_contain_any any='[types field='my-checkboxes' separator=','][/types]' test='9,10,11,12'] eq '1' )"] [cred form="Cred form 3"] [/wpv-conditional]
Replace the test values like 1,2,3,4 in each conditional with a comma-separated list of checkbox values. Replace my-checkboxes with the slug of your checkboxes group custom field. If any of the corresponding checkboxes are checked, The CRED form contained in the conditional will be displayed.