How to use WordPress Rest API to show search result content in 3 efficient steps?

In previous post we have got basic inforamtion how to use WordPress Rest API. In this post we will understand how to use WordPress Rest API in more prcatical exmple, which is getting search result content dynamically withou reloading the page.

We have covered the basic of the creation of the search result overlay in one of my previous the posts, here we are going to discuss the porcess of getting the informtion we need from the posts/pages.

Step 1: How to use wordpress Rest API

To sart using we first need to initialize the events. Let’s wrap the methods we are going to use inside jQuery’s ready function to make sure that we access DOM when our elements are already initialized.

Our second step will be getting saving our input element from DOM into a variable.

Pro Tips: Always try to save DOM element into a varaible if you are going to use it more then one time. Accessing DOM is very slow compared to lightening fast java script variables.

how to use wordpress rest api
How to use wordpress Rest API -First step

Step 2: Sending AJAX reuest and getting the information from databse

Now we need to crete methods which start to fire as soon as the user types what he/she searches for. Basically what we need to use input/keyup or keydown events and fire search by the typed letters/words.

For this we will create getResults function which will start collecting the data as soon as the user keyup function happens.

getJson” native function of jQuery comes on very handy for our case, we pass the Rest API path with search ending and add to it what the user has typed in as the first argument. Make sure to call getResult function too inside your event.

how to use wordpress rest api - step 2/1
How to use wordpress rest api – step 2/1

The second argument is the function which contains the inforamtion we get from Json. We can give to the function any argument, which will contain all the information we got in an array of objects. Then we can access the objects and print them to our front end using “for each” loop.

how to use wordpress rest api - step 2/2
How to use wordpress rest api – step 2/2

After we make sure that our code is written correctly and we we errors in our console, we will be able to see the results in the console. I have created two posts about rabbits, where I tell how fast the rabbits are, just for a test to make sure that we get the content we need from the post according to our input data.

how to use wordpress rest api - step 2/2
How to use wordpress rest api – As you can see the results -the titles of posts including in search results are printed to console successfully.

As we can see in console the results are being printes to console successfully. Now let’s make some esthetic changes so as we are sure that what we do works good for the user. Practically at this step already amnaged to get information from database we will just make sure to display them correctly on front end.

Step 3: Showing results on front-end

Right now we get full results from the database and we already understood how to use WordPress Rest API, but we can see following problems in what we have:

  1. We run getResult function every time the user types a letter which is kind of messy and makes bad user experiance. Rather we need to start searching after amout a secons as soon as the user stoppes typing.
  2. There is no any interaction at the moment about the process that happens to the user while he/she is typing here we can show a spinner loading icon.

Waiting before showing results

Java Script has a nice inbuilt function calles “setTimeout“. It takes two arguments. First is the function which is being executed and the secont is the time in mliliseconds it needs to wait before being executed.

Let’s instead of calling for getResult function first wrap it inside setTimeout and wait for 2000 miliseconds before executin. We just need to have the following code:

setTimeout( getResults, 2000 )

But we need to clear timeout later every time user stops typing, so lets first keep it inside a varible so as we can use more functionality later

typingTimer = setTimeout( getResults, 2000 )

Before we move on let’s make sure we are not searching for the same word if user stopped typing over and over again, so let’s keep the value after searching into a variable and run the search again if only the input value is not equal to the previous value of the search.

For this we need to declare an empty variable which will hold the value of the input and will be constantly updated every time another search is being performed(remember we need to run search again only if the value in this variable won’t be equal to what is in the input)

Spinner loading icon

Let’s make a variable called isSpinnerActive, which is not going to have any value at all, which is going to have a boolean value later.

Then we do an if statement telling if our spinner is false(which is not initially), we make innerHtml of our results div an element containing class spinner which is going to make sure that our soinner icon shows as we need and we make isSpinnerActive true. After if statement we add the following code:

typingTimer = setTimeout( getResults, 2000);

So what we have done by now we check if isSpinnerActive is false we make it true, we show the spinner and we run getResults function. Here is the code

//How to use wordpress rest api - step 3 - showing the spinner

searchForm.addEventListener("keyup", () => {

      if ( searchForm.value != oldValue ) {

        clearTimeout( typingTimer )

        if ( searchForm.value ) {

          if ( !isSpinnerActive ) {
            showResults.innerHTML = "<div class='spinner'></div>";
            isSpinnerActive = true
          }
          typingTimer = setTimeout( getResults, 2000);
        } else {
          showResults.innerHTML = "<div class='spinner'></div>";
          isSpinnerActive = false
        }
        
      } 

      
      oldValue = searchForm.value

    })
  
 //How to use wordpress rest api - step 3 - showing the spinner

Then in else secition(this happens initially when user is still typing), we just show spinner and make isSpinnerActive false. That is it our spinner icon works too.

Let’s also make sure we show results not just in console but we show the results to the visitor and this is the last step of understanding how to use wordpress Rest API.

//How to use wordpress rest api - step 3 - showing the spinner
//Here we show results using templatre literals which help us keep content on different lines.
function getResults() {
      //console.log(document.getElementById("search-form-1"))
      jQuery.getJSON("/wp-json/wp/v2/posts?search=" + document.getElementById("search-form-1").value, function (posts) {
        showResults.innerHTML = (`
        <h2 class="search-overlay__section-title">General Information</h2>
        ${posts.length ? '<ul class="link-list min-list">' : "<p>No general information matches that search.</p>"}
          ${posts.map(item => `<li><a href="${item.link}">${item.title.rendered}</a></li>`).join("")}
        ${posts.length ? "</ul>" : ""}
        `)
        isSpinnerActive = false
      })

    }

Note: Make sure to use template literals not colons or double colons otehrwise you will get errors on console and the function won’t work.

Katen Doe

Hovhannes Verdyan

Hello, I’m a developer who loves WordPress and loves helping peopls let me know if you have any question by leaving your question in comments in one of my youtube videos. Click here to go to my channel.