Caldera Forms – Setting up Conditional Logic based on a post’s taxonomy term

I was trying to set up the following using Caldera Forms’ Conditional Group. This log is based on Caldera Forms 1.7.2.

In my form, I needed a Select field X that was auto populated with a list of every post of a custom post type. This can be easily achieved by selecting ‘Auto Populate’ and choosing ‘Post Type’ when setting up the field using Caldera Forms’ UI. More details can be found under the section ‘Auto-populating Caldera Forms Select Field Options’ in the documentation.

When a user selects an option in field X, I needed another field Y to be hidden or shown based on field X selected option’s taxonomy term (i.e. the selected post’s taxonomy term); if it belonged to taxonomy term Z, then field Y should be hidden.

Caldera Forms’ conditional logic doesn’t provide such logic out of the box – there was no method to check a taxonomy term against the selected option.

To work around, I had to include the taxonomy term slug as part of the value of each option (in field X), with which I can then make use as a condition to check against when setting up the conditional group. However, the ‘Auto Populate’ method mentioned above does not allow us to set the taxonomy term slug as part of each option’s value.

Caldera has a caldera_forms_render_get_field filter that allows us to customise auto populated fields. So we’ll code this:

add_filter( 'caldera_forms_render_get_field', function( $field )  {
    if ( 'field_X_slug' == $field[ 'slug' ]  ) {
        $args = array(
            'post_type' => 'custom-post-type',
            'order' => 'ASC',
            'orderby' => 'title',
            'posts_per_page' => -1,
        );

        $myposts = get_posts( $args );

        if ( ! empty( $myposts ) ) {
            foreach( $myposts as $post ) {
                $post_terms = get_the_terms( $post->ID , 'custom-taxonomy' );
                $field_value = array();
                foreach ( $post_terms as $post_term ) {
                    $field_value[] = $post_term->slug;
                }
                $field_value[] = $post->post_name;
                $field[ 'config' ][ 'option' ][ $post->ID ] = array(
                    'value' => '_' . implode( "_", $field_value ),
                    'label' => wp_strip_all_tags( $post->post_title, true )
                );
            }
        }
    }
    return $field;
});

This results in field X’s options having values that look something like ‘_tax-term-Z_tax-term-AZ_post-slug’.

Having the above, we can then set up a conditional group by setting up a conditional line that hides field Y if field X CONTAINS _tax-term-Z_.

Leave a Comment