WooCommerce Product Search Autosuggest

User
add auto suggestion to search box for woocomerce product jquery and php
Assistant
Adding an auto-suggestion feature to your WooCommerce product search box using jQuery and PHP involves these steps:

### 1. **Frontend: Add the Search Box**
Ensure your search box has a unique ID or class for targeting with jQuery.

<input type="text" id="product-search" placeholder="Search for products..." />
<div id="suggestion-box"></div>

### 2. **Frontend: jQuery for Fetching Suggestions**
Add a script to handle the AJAX request and display suggestions dynamically.

jQuery(document).ready(function ($) {
    $('#product-search').on('keyup', function () {
        let query = $(this).val();

        if (query.length > 2) { // Trigger AJAX if input length > 2
            $.ajax({
                url: '/wp-admin/admin-ajax.php', // WordPress AJAX handler
                type: 'POST',
                data: {
                    action: 'fetch_product_suggestions', // Custom action name
                    query: query
                },
                success: function (data) {
                    $('#suggestion-box').html(data).show();
                },
            });
        } else {
            $('#suggestion-box').hide(); // Hide suggestions if input is short
        }
    });

    // Hide suggestion box when clicking outside
    $(document).on('click', function (e) {
        if (!$(e.target).closest('#product-search, #suggestion-box').length) {
            $('#suggestion-box').hide();
        }
    });
});

### 3. **Backend: Create AJAX Handler**
Use PHP to query WooCommerce products based on the user's input.

Add this to your theme's `functions.php`:

function fetch_product_suggestions() {
    if (isset($_POST['query'])) {
        $query = sanitize_text_field($_POST['query']);

        // Query WooCommerce products
        $args = [
            'post_type' => 'product',
            'posts_per_page' => 10,
            's' => $query, // Search query
        ];
        $query_results = new WP_Query($args);

        if ($query_results->have_posts()) {
            echo '<ul>';
            while ($query_results->have_posts()) {
                $query_results->the_post();
                echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
            }
            echo '</ul>';
        } else {
            echo '<p>No products found</p>';
        }

        wp_reset_postdata();
    }
    wp_die(); // Required to terminate AJAX request properly
}
add_action('wp_ajax_fetch_product_suggestions', 'fetch_product_suggestions');
add_action('wp_ajax_nopriv_fetch_product_suggestions', 'fetch_product_suggestions');

### 4. **Style the Suggestion Box**
Add CSS for the suggestion box to make it visually appealing.

#suggestion-box {
    border: 1px solid #ccc;
    background-color: #fff;
    position: absolute;
    width: 100%;
    z-index: 1000;
    display: none;
}

#suggestion-box ul {
    list-style: none;
    margin: 0;
    padding: 0;
}

#suggestion-box ul li {
    padding: 10px;
    border-bottom: 1px solid #eee;
}

#suggestion-box ul li:hover {
    background-color: #f0f0f0;
}

#suggestion-box ul li a {
    text-decoration: none;
    color: #333;
}

### 5. **Testing**
1. Type a few characters in the search box.
2. Verify that suggestions load dynamically.
3. Check links to ensure they lead to the correct product pages.

Let me know if you encounter any issues!

User
also add categiory search and it will go to category page
Assistant
To add category search functionality alongside product search and redirect the user to the appropriate category page when selected, we need to modify the implementation as follows:

### 1. **Update the Frontend Search Box**

Add a dropdown for selecting search type (products or categories):

<div>
    <select id="search-type">
        <option value="product">Product</option>
        <option value="category">Category</option>
    </select>
    <input type="text" id="search-input" placeholder="Search for products or categories..." />
    <div id="suggestion-box"></div>
</div>

### 2. **Update jQuery for Handling Categories**

Update the script to fetch both product and category suggestions and handle redirection for category clicks:

jQuery(document).ready(function ($) {
    $('#search-input').on('keyup', function () {
        let query = $(this).val();
        let searchType = $('#search-type').val();

        if (query.length > 2) {
            $.ajax({
                url: '/wp-admin/admin-ajax.php',
                type: 'POST',
                data: {
                    action: 'fetch_suggestions',
                    query: query,
                    type: searchType,
                },
                success: function (data) {
                    $('#suggestion-box').html(data).show();
                },
            });
        } else {
            $('#suggestion-box').hide();
        }
    });

    // Handle clicking on category links
    $(document).on('click', '#suggestion-box a.category-link', function (e) {
        e.preventDefault();
        window.location.href = $(this).attr('href'); // Redirect to the category page
    });

    // Hide the suggestion box when clicking outside
    $(document).on('click', function (e) {
        if (!$(e.target).closest('#search-input, #suggestion-box, #search-type').length) {
            $('#suggestion-box').hide();
        }
    });
});

### 3. **Update PHP AJAX Handler**

Modify the PHP handler to fetch both products and categories based on the selected type.

Add this to `functions.php`:

function fetch_suggestions() {
    if (isset($_POST['query'], $_POST['type'])) {
        $query = sanitize_text_field($_POST['query']);
        $type = sanitize_text_field($_POST['type']);

        if ($type === 'product') {
            // Fetch products
            $args = [
                'post_type' => 'product',
                'posts_per_page' => 10,
                's' => $query,
            ];
            $query_results = new WP_Query($args);

            if ($query_results->have_posts()) {
                echo '<ul>';
                while ($query_results->have_posts()) {
                    $query_results->the_post();
                    echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
                }
                echo '</ul>';
            } else {
                echo '<p>No products found</p>';
            }
        } elseif ($type === 'category') {
            // Fetch categories
            $categories = get_terms([
                'taxonomy' => 'product_cat',
                'name__like' => $query,
                'number' => 10,
            ]);

            if (!empty($categories) && !is_wp_error($categories)) {
                echo '<ul>';
                foreach ($categories as $category) {
                    echo '<li><a class="category-link" href="' . get_term_link($category) . '">' . $category->name . '</a></li>';
                }
                echo '</ul>';
            } else {
                echo '<p>No categories found</p>';
            }
        }

        wp_die(); // Terminate AJAX request
    }
}
add_action('wp_ajax_fetch_suggestions', 'fetch_suggestions');
add_action('wp_ajax_nopriv_fetch_suggestions', 'fetch_suggestions');

### 4. **CSS for Suggestion Box**

No changes are needed unless you want to style category suggestions differently:

#suggestion-box ul li a.category-link {
    font-style: italic;
    color: #0073aa;
}

### 5. **Behavior**

1. **Search Type Selection**: Users select either "Product" or "Category" in the dropdown.
2. **Dynamic Suggestions**: As the user types, suggestions for the selected type (products or categories) are displayed.
3. **Redirection for Categories**: Clicking on a category suggestion redirects the user to the category page.

### 6. **Testing**

1. Test searching for products and ensure suggestions link to the correct product pages.
2. Test searching for categories and confirm redirection to the correct category pages.
3. Verify functionality across browsers and devices.

Let me know if you need additional customizations!

Leave a Comment

Your email address will not be published. Required fields are marked *