WordPress Fast Realtime Search wp-json rest

this is a very very very fast search for WordPress posts and pages.

It uses the wp-rest and because there is no ajax it is just reading the existing rendered data from the wp-rest performance is really good.

if you have a big website with big traffic definitely use this with wp-rest cache plugin.

<div class="prefix-test-wrapper">
    <input type="text" id="search-input" placeholder="Type to search..." style="width: 100%; padding: 8px; margin: 10px 0;">
    <div id="search-results" style="margin-top: 20px;"></div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const input = document.getElementById('search-input');
    const resultsDiv = document.getElementById('search-results');

    input.addEventListener('input', function() {
        if (input.value.length > 0) {
            fetch(`/wp-json/wp/v2/search?search=${encodeURIComponent(input.value)}`)
                .then(response => response.json())
                .then(results => {
                    resultsDiv.innerHTML = ''; // Clear previous results
                    results.forEach(result => {
                        const a = document.createElement('a');
                        a.textContent = result.title; // Assuming 'title' is the desired display property
                        a.href = result.url; // Assuming 'url' contains the link to the content
                        a.style.display = 'block'; // Make each result a block element
                        a.style.marginBottom = '10px'; // Add some spacing between results
                        resultsDiv.appendChild(a);
                    });
                })
                .catch(error => {
                    console.error('Error:', error);
                    resultsDiv.innerHTML = '<p>Error loading results.</p>';
                });
        } else {
            resultsDiv.innerHTML = ''; // Clear results when input is cleared
        }
    });
});
</script>

Leave the first comment

Hello 🖐 Welcome

I am planning a professional WordPress and Bricks Builder course. If you are Interested register to this newsletter.