Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <p><strong>Search the site:</strong></p>
- <p><input type="text" id="searchQuery" placeholder="Search..." class="wp-block-search__input">
- <button onclick="performSearch()">Search</button></p>
- <p><b>Search Results</b></p>
- <ul id="results" style="list-style: disc;list-style-position: inside;"></ul>
- <script src="https://<static-host>/search/lunr.js"></script>
- <script>
- // Load the JSON index and create Lunr index
- let idx, documents;
- async function loadIndex() {
- const response = await fetch('https://<static-host>/search/blog-json-all.json'); // URL to your JSON index from step 1
- documents = await response.json();
- // Create Lunr index
- idx = lunr(function () {
- this.ref('id');
- this.field('title');
- this.field('content');
- documents.forEach(function (doc) {
- this.add(doc);
- }, this);
- });
- }
- // Perform the search
- async function performSearch() {
- const query = document.getElementById('searchQuery').value;
- if (!idx) {
- await loadIndex(); // Ensure index is loaded
- }
- const results = idx.search(query);
- // Display the search results
- const resultsContainer = document.getElementById('results');
- resultsContainer.innerHTML = ''; // Clear previous results
- if (results.length === 0) {
- resultsContainer.innerHTML = '<li>No results found<\/li>';
- return;
- }
- results.forEach(result => {
- const doc = documents.find(d => d.id === result.ref);
- const listItem = document.createElement('li');
- listItem.innerHTML = `<a href="${doc.url}">${doc.title}<\/a>`;
- resultsContainer.appendChild(listItem);
- });
- }
- // Load the index when the page loads
- document.addEventListener('DOMContentLoaded', loadIndex);
- </script>
- </div>
Advertisement
Add Comment
Please, Sign In to add comment