wordpress 实时WooCommerce产品搜索不显示结果

vom3gejh  于 2023-06-21  发布在  WordPress
关注(0)|答案(1)|浏览(218)

为我的WooCommerce产品循环创建搜索过滤器时,键入产品名称时不显示结果。在我将product_cat添加到查询中之前,这是按预期工作的。
如何调整代码以显示product循环,同时向查询中添加产品类别数组,以便可以实时筛选结果?
所需输出:
用户键入显示的产品名称。如果我取消选择一个产品,它将不会是查询的一部分。

function realtime_product_search_enqueue_scripts() {
    wp_enqueue_script('realtime-product-search', plugin_dir_url(__FILE__) . 'realtime-product-search.js', array('jquery'), '1.0', true);
    wp_localize_script('realtime-product-search', 'realtime_product_search_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'realtime_product_search_enqueue_scripts');

// AJAX callback function for product search
function realtime_product_search_callback() {
    $search_term = sanitize_text_field($_POST['search_term']);
    $category_filter = isset($_POST['category_filter']) ? $_POST['category_filter'] : '';

    $args = array(
        'post_type' => 'product',
        's' => $search_term,
        'posts_per_page' => 10,
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field' => 'slug',
                'terms' => $category_filter,
                'operator' => 'IN',
            ),
        ),
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            global $product;
            $product_id = get_the_ID();
            
            // Output the product information as needed
            echo '<div class="product">';
            echo '<h2>' . get_the_title($product_id) . '</h2>';
            echo '<div class="product-thumbnail">' . $product->get_image() . '</div>';
            echo '<div class="product-add-to-cart">' . $product->add_to_cart_button() . '</div>';
            echo '</div>';
        }
    } else {
        echo '<p>No products found.</p>';
    }

    wp_reset_postdata();
    die();
}

add_action('wp_ajax_realtime_product_search', 'realtime_product_search_callback');
add_action('wp_ajax_nopriv_realtime_product_search', 'realtime_product_search_callback');

// Shortcode implementation
function realtime_product_search_shortcode() {
    ob_start();

    // Get product categories
    $categories = get_terms(array(
        'taxonomy' => 'product_cat',
        'hide_empty' => true,
    ));

    ?>
    <div class="realtime-product-search">
        <input type="text" id="product-search" placeholder="Search for products..." />
        <div id="category-filter">
            <h4>Filter by Category:</h4>
            <?php foreach ($categories as $category) : ?>
                <label>
                    <input type="checkbox" name="category_filter[]" value="<?php echo $category->term_id; ?>" />
                    <?php echo $category->name; ?>
                </label>
            <?php endforeach; ?>
        </div>
        <div id="search-results"></div>
    </div>
    <?php

    return ob_get_clean();
}
add_shortcode('realtime_product_search', 'realtime_product_search_shortcode');

JS文件

jQuery(document).ready(function ($) {
    var typingTimer;
    var doneTypingInterval = 500; // Delay in milliseconds before AJAX request is sent

    $('#product-search').on('input', function () {
        clearTimeout(typingTimer);
        if ($('#product-search').val()) {
            typingTimer = setTimeout(realtimeProductSearch, doneTypingInterval);
        }
    });

    function realtimeProductSearch() {
        var search_term = $('#product-search').val();

        $.ajax({
            url: realtime_product_search_ajax.ajax_url,
            type: 'post',
            data: {
                action: 'realtime_product_search',
                search_term: search_term
            },
            success: function (response) {
                $('#search-results').html(response);
            }
        });
    }
});
axr492tv

axr492tv1#

下面是代码的更新版本

// Shortcode implementation
function realtime_product_search_shortcode() {
    ob_start();

    // Get product categories
    $categories = get_terms(array(
        'taxonomy' => 'product_cat',
        'hide_empty' => true,
    ));?>
    <div class="realtime-product-search">
        <input type="text" id="product-search" placeholder="Search for products..." />
        <div id="category-filter">
            <h4>Filter by Category:</h4>
            <label>
                <input type="checkbox" name="category_filter[]" value="" /> Any Category
            </label>
            <?php foreach ($categories as $category) : ?>
                <label>
                    <input type="checkbox" name="category_filter[]" value="<?php echo $category->term_id; ?>" />
                    <?php echo $category->name; ?>
                </label>
            <?php endforeach; ?>
        </div>
        <div id="search-results"></div>
    </div>
    <?php return ob_get_clean();
}
add_shortcode('realtime_product_search', 'realtime_product_search_shortcode');

查询部分

function perform_product_search() {
    $searchQuery = isset($_POST['search_query']) ? sanitize_text_field($_POST['search_query']) : '';
    $categoryFilter = isset($_POST['category_filter']) ? $_POST['category_filter'] : array();

    $args = array(
        'post_type' => 'product',
        'post_status' => 'publish',
        's' => $searchQuery,
    );

    if (!empty($categoryFilter)) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => $categoryFilter,
                'operator' => 'IN',
            ),
        );
    }

    $query = new WP_Query($args);

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            // Display your product information here (e.g., title, image, price, etc.)
            the_title('<h3>', '</h3>');
        }
        wp_reset_postdata();
    } else {
        echo 'No products found.';
    }

    die();
}
add_action('wp_ajax_perform_product_search', 'perform_product_search');
add_action('wp_ajax_nopriv_perform_product_search', 'perform_product_search');

jquery

(function($){
    $(document).ready(function ($) {
        var typingTimer;
        var doneTypingInterval = 500; // Adjust the interval as needed (in milliseconds)
        
        function performProductSearch() {
            clearTimeout(typingTimer);
            
            typingTimer = setTimeout(function() {
                var searchQuery = $('#product-search').val();
                var categoryFilter = [];
        
                $('input[name="category_filter[]"]:checked').each(function() {
                    var value = $(this).val();
                    if (value !== '') {
                        categoryFilter.push(value);
                    }
                });
        
                $.ajax({
                    url: realtime_product_search_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'perform_product_search',
                        search_query: searchQuery,
                        category_filter: categoryFilter
                    },
                    beforeSend: function() {
                        $('#search-results').html('Searching...');
                    },
                    success: function(response) {
                        $('#search-results').html(response);
                    }
                });
            }, doneTypingInterval);
        }
        
        // Trigger search on input change
        $('#product-search, input[name="category_filter[]"]').on('change keyup', function() {
            performProductSearch();
        });
    });
    
})(jQuery);

相关问题