Support

Account

Home Forums Feature Requests Conditional Logic using Taxonomy field Reply To: Conditional Logic using Taxonomy field

  • Like many I also wanted to have conditional fields related to a taxonomy and I solved this issue with only 14 lines of code (not counting commented lines)… I think several people may benefit from this.

    I first had a simple radio button as for a custom field called sex.
    Based upon this selection some other fields came into action, such as cup size for women.

    I then decided to make a taxonomy for sex. I didn’t add an ACF field for it. Instead I added an acf/save_post action, which changes the taxonomy on post save, based on the value which was entered in the ACF field.

    So the page loads the custom field value and on save it changes the taxonomy if those values are not the same.

    Add this to functions.php

    
    function change_post_taxonomy_44582( $post_id ) {
        // bail if no ACF data
        if ( empty($_POST['acf']) ) {
            return;
        }
        // get term id from $post_id (only 1 value is allowed, so it returns 1 value only)
        $stored_sex = wp_get_post_terms($post_id, 'sd_sex');
        // get submitted value from acf form
        $posted_sex = $_POST['acf']['field_57e3ed6c92fd1'];
        // get term_id for the submitted value
        $term_id    = get_term_by( 'name', $posted_sex, 'sd_sex' );
        // if stored value is not equal to posted value, then update terms
        if ( $stored_sex != $posted_sex ) {
            wp_set_object_terms( $post_id, $term_id->term_id, 'sd_sex' );
        }
    }
    add_action('acf/save_post', 'change_post_taxonomy_44582', 20);
    
    

    Hope this helps some people.