Support

Account

Home Forums Front-end Issues Insert term if typing in select option new value

Solving

Insert term if typing in select option new value

  • I have issue with inserting terms while typing select input field. Strings will be correctly inserted but if there is date or number values for terms then it inserts term ID.

    I have a lot term fields and some of them are numeric fields like date, mileage, etc..

    My Code:

    function jl_insert_term_if_not_exists($term, $taxonomy) {
        if (empty($term) || is_numeric($term)) { //tried is_string() then every value inserted as term ID
            return $term;
        }
    
        if ($result = term_exists($term, $taxonomy)) {
            return $result['term_id'];
        }
    
        $result = wp_insert_term($term, $taxonomy);
    
        if (!is_wp_error($result)) {
            return $result['term_id'];
        }
    }
    
    function jl_acf_update_value( $value, $post_id, $field ) {
        if ($field['type'] == 'taxonomy'
            && in_array($field['field_type'], array('select', 'multi_select'))
            && strpos($field['wrapper']['class'], 'acf-select-tags') !== false)
        {
            if (!is_array($value)) {
                if ($term_id = jl_insert_term_if_not_exists($value, $field['taxonomy'])) {
                    $value = $term_id;
                }
            } else {
                foreach ($value as &$item_value) {
                    if ($term_id = jl_insert_term_if_not_exists($item_value, $field['taxonomy'])) {
                        $item_value = $term_id;
                    }
                }
            }
        }
    
        return $value;
    }
    add_filter('acf/update_value', 'jl_acf_update_value', 5, 3);
    function jl_acf_input_admin_footer() {
    ?>
    <script type="text/javascript">
        (function($) {
            acf.add_filter('select2_args', function( args, $select, settings, $field, instance ){
                if ($field.hasClass('acf-select-tags')) {
                    console.log($field.hasClass('acf-select-tags'));
                    args.tags = true
                }
                
                return args;
            });
        })(jQuery);
    </script>
    <?php
    }
    add_action('acf/input/admin_footer', 'jl_acf_input_admin_footer');
  • Anyone has same issue?

  • You have some issues in your code, for example this

    
    if ($result = term_exists($term, $taxonomy)) {
    

    should probably be

    
    if ($result == term_exists($term, $taxonomy)) {
    

    there are several of this same type of error in the code that you’ve posted.
    This is usually why some people code like this

    
    if (term_exists($term, $taxonomy) == $result) {
    

    because the above would create an error if you use ‘=’ instead of ‘==’ rather than fail quietly.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.