admin管理员组

文章数量:1125774

The array in this function return 0. I am unable to figure out what the problem is.

function custom_woocommerce_auto_suggest() {
    $search_query = sanitize_text_field($_POST['search_query']);

    $args = array(
        's' => $search_query,
        'post_type' => 'product',
        'posts_per_page' => 5,
        'tax_query' => array(
            'relation' => 'OR',
            array(
                'taxonomy' => 'product_cat',
                'field' => 'name',
                'terms' => $search_query,
            ),
        ),
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key' => '_sku',
                'value' => $search_query,
                'compare' => '%LIKE%',
            ),
            array(
                'key' => '_product_attributes',
                'value' => $search_query,
                'compare' => 'LIKE',
            ),
        ),
    );

    $query = new WP_Query($args);
    $suggestions = array();

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            $suggestions[] = get_the_title();
        }
        wp_reset_postdata();
    }

    echo wp_send_json($suggestions);

    wp_die(); 
}

This is Jquery autocomplete code.

jQuery(document).ready(function($) {
    // ... Your existing code ...
    console.log('Autocomplete initialized'); 

    // Autocomplete functionality
    $('#search-input').autocomplete({
        source: function(request, response) {
            $.ajax({
                type: 'POST',
                url: custom_woocommerce_search_params.ajax_url,
                data: {
                    action: 'custom_woocommerce_auto_suggest',
                    search_query: request.term,
                },
                success: function(data) {
                    response(data);
                    console.log(data);
                },
                error: function(error) {
                    console.log('Error:', error);
                }
            });
        },
        minLength: 2, // Minimum characters before triggering autocomplete
        select: function(event, ui) {
            // Handle selection if needed
        }
    });
});

本文标签: phpWhy jquery arrray return 0 value