Format JSON Data to Display Results
Explore how to format JSON data received from the WordPress REST API to display search results dynamically. Learn to update the search results area with multiple items, handle empty responses gracefully, and move HTML structure into JavaScript for better integration. This lesson helps you create interactive, user-friendly search functionality in custom WordPress themes.
We'll cover the following...
Formatting JSON data
Open the Search.js file from the modules folder inside the src folder. The Search class has a sendSearchRequest method which sends a request to the WordPress REST API. We will work on displaying the results in this lesson.
In the previous lesson, we displayed the title of the posts on the console. Now we will adjust the markup of the search-results div to display the title under the input box. The sendSearchRequest method from the last lesson is reproduced below:
sendSearchRequest(){fetch(siteData.root_url+ '/wp-json/wp/v2/event?search='+this.searchInput.value).then((response)=>{return response.json();}).then((data)=>{console.log( data.map(function(element){return `${element.title.rendered}`;}));});this.isSpinning = false;}
Recall, that the <div> that displays the search results is contained in the searchResults property.
constructor(){//other propertiesthis.searchResults = document.querySelector("#search-results");//...}
Open the terminal in VS Code by clicking the "View" option and choosing "Terminal." Run the start script using the
npm run startcommand. The start script will watch for any changes in the code and recompile it.
We will target the innerHTML property of searchResults to output ...