wordpressselectize.js

How can i use selectize in wordpress


I need to use Selectize in wordpress ajax. I have a selecto tag, I want to search by entering words and display the results in a dropdown. It is also possible to select several items and delete them. I tried to do this with the code below but only the output in console.log is displayed as an array.

<select id="variations" name="variations[]" class="form-control variation-input" multiple></select>

PHP Code:

add_action('wp_ajax_search_terms', function () {
    $terms = get_terms([
        'taxonomy' => 'pa_colors',
        'hide_empty' => false,
        'search' => $_POST['search']
    ]);
    foreach ($terms as $term) {
        $return[] = array($term->term_id, $term->name);
    }
    echo json_encode($return);
    wp_die();
});

Js Code:

    $('.variation-input').selectize({
        plugins: ["clear_button","remove_button"],
        valueField: 'id',
        labelField: 'name',
        searchField: 'name',
        options: [],
        delimiter: ',',
        preload: true,
        persist: false,
        create: false,
        load: function (query, callback) {
            if (!query.length) return callback();
            $.ajax({
                // type: 'GET',
                type: 'post',
                url: sudJs.ajax_url,
                dataType: 'json',
                data: {
                    action: 'search_terms',
                    name: query,
                },
                error: function () {
                    console.log('error');
                    callback();
                },
                success: function (result) {
                    console.log(result);
                    callback(result);
                }
            });
        },
    });

Console.log Return array of terms, but not showing in selectize.


Solution

  • There are few issues which needs to be address to make this workable, so here is the updated code which can be used to achieve desired functionality.

    In this code we have corrected the format of returned array because previous PHP code returns an array of arrays which is not the desired one.

    add_action( 'wp_ajax_search_terms', function () {
        $terms = get_terms( [
            'taxonomy'   => 'pa_colors',
            'hide_empty' => false,
            'search'     => $_POST['name'], // We need to use name instead of search to match the JS Code.
        ] );
    
        $return = []; // This is to initialize the return array.
        foreach ($terms as $term) {
            $return[] = [
                'id'   => $term->term_id, // This is to ensure this matches our valueField.
                'name' => $term->name,   // This is to ensure this matches our labelField.
            ];
        }
    
        echo json_encode( $return );
        wp_die(); // This is important to terminate the script.
    });
    

    Also in the given code we have correctly configured the fields according to PHP code.

    $( '.variation-input' ).selectize({
        plugins: ["clear_button", "remove_button"],
        valueField: 'id',      // This should matches the "id" from the PHP return.
        labelField: 'name',     // This should matches the "name" from the PHP return.
        searchField: 'name',    // This is the field we are searching.
        options: [],
        delimiter: ',',
        preload: true,
        persist: false,
        create: false,
        load: function ( query, callback ) {
            if ( ! query.length ) return callback();
            $.ajax({
                type: 'post',
                url: sudJs.ajax_url,
                dataType: 'json',
                data: {
                    action: 'search_terms',
                    name: query, // This is to ensure the key matches what the PHP function expects.
                },
                error: function () {
                    console.log('Error occurred during the AJAX request.');
                    callback([]);
                },
                success: function (result) {
                    console.log(result); // This is to debug the output.
                    callback(result); // This is to pass the result to Selectize.
                }
            });
        },
    });