The best way of setting up the layout for advanced search for WordPress and keep your website at ease

Setting up the advanced search for WordPress can be tricky especially when you need much custom configuration and post/pages functionality.

Please note that this tutorial requires from you minimal knowledge of PHP and front-end technologies. There are a bunch of advanced search plugins for WordPress that you can use in many cases when you need some standard solutions but in today’s competitive world what you need to attract visitors’ attention is something different and outside of the box.

First of all, let’s understand what is live or advanced search in WordPress. To understand this let me show you an example in the image below.

If you would like to see explanations and details in the video follow this link to my youtube channel video or see more on my blog page about WordPress and custom solutions.

Advanced search for WordPress
Here you see what does not happen in advanced search for WordPress

In the image above you see an input area with the button called “Search” next to it. After you input the word or expression you want to find on the website, you click the button, and then you are redirected to the search page(called search.php), where you see all the content containing the word/expression you searched for.

In the case of live or advanced search for WordPress, you see the content in real-time without a need to reload the page. This is a nice option which all the visitors like.

Step 1: Creating and styling search form layout

Our first action will be the creation of our search form layout which is going to open as soon as the user clicks the search button on the right corner.

Our layout will add opacity to the body element so as the rest of the elements don’t interfere with the rest of the content. Let’s start by writing some JavaScript.

//Let's start coding our search form layout class which is responsible for front-end of our form.
<style>
  
.search-overlay {
  display: none; 
}

.search-overlay__active {
  display: block; 
}

.no-scroll {
  overflow: onone;
}
  
</style>

<script>
  class Search {
    // 1. Describe and create/initiate our object
    constructor() {
      this.openLayout = jQuery(".search-trigger") //Your button openong the layout
      this.closeLayout - jQuery(".close-trigger") //Your close button class/ID
      this.searchLayout = jQuery(".actual-alayout") //The actual layout of our search form
      this.isOverlayOpen = false 
      this.events()
    }
  
    // 2. events
    events() {
      this.openLayout.on("click", this.openLayout.bind(this))// Make sure the value of "this" keyword is not being changed
      this.openLayout.on("click", this.closeLayout.bind(this))
      //Adding optionality of closing the layout when pressed ESC key.
      $(document).on("keyup", this.keyPresser.bind(this))
    }
  
    // 3. methods functions/actions
    function openLayout(){
      this.searchLayout.addClass("search-overlay__active")
      $("body").addClass("no-scroll")//Stop scrolling when layout is open
      this.isOverlayOpen = true 
    }
  
    function closeLayout(){
      this.searchLayout.removeClass("search-overlay__active")
      $("body").removeClass("no-scroll")//Stop scrolling when layout is open
      this.isOverlayOpen = false 
    }
  
    function keyPresser(e) {
      //s key to open the layout
      if ( e.keyCode == 83 && !this.isOverlayOpen ){
        this.openLayout()
      }
      
      //ESC key to close layout
      if ( e.keyCode == 27 && this.isOverlayOpen){
        this.closeLayout()
      }
    }
  }

  export default Search
    
  //Make sure to import it later and use in the actual file you arew going to use it
  import Search from "./modules/search"//You don't need to write down here .js here, just file name
    
  //Creating a new object. Now when we have the class we can create as many objects and 
  //instances as we need
  const liveSearch = new Search()
    
//Here is actual HTML that can will be in the header of the website
</script>
    
 <div class="search-overlay">
    <div class="search-overlay-inner">
      <div class="container">
        //Here you put your elements as in your design
      </div>
    </div>
 </div>

Code explanation:

  1. Class – line 19. We create a class which can be called in multiple ocations. This helps us to write cleaner and faster code. Using classes is extremely helpful when working on big projects.
  2. This keyword – This represents the object we are referring to. For example on line 30 when we use this before openLayout, we tell to browser that we refer to the function created on line 35.
  3. Finding out hte code of the key – In ny example we use the ESC key to close the search form layout of our advanced search for WordPress, but let’s imaging you want to use other key for other event. Just console log e.keyCode and find out the code you need.
  4. Keyup event – We can also use keydown here, but for our instance if we use it the action is going to run again and again while you are hoding down the key, which may become of heavy performance in the browser.
  5. isOverlayOpen – We created this variable in order to check if the layout is open or now and use it in condtions. You may be asking yourself why not just check if our layout has a class of active or no? The reason we use boolean to check if it is open or no we need is that dealing with the DOM is very slow and we shall avoid it any time it is possible.

That is it for the layout. We managed to create the opening and closing layout which is good and effective in interacting with the browser. Let’s move to the next point of our job. Which is managing with the results will be showing when the users types in.

An example of search form layout being open after the click

Step 2: How to manage time in javascript?

After the search form is open the visitor of the website will start typing what they are searching for. As described above the results will need to pop up in real-time using AJAX requests.

Right now we don’t care that AJAX requests and getting information from REST API are not set up. We are just setting up the layout at the moment.

When the user types in we need to wait for about 800ms until we start showing the results and wait for another second until we show updated results again, otherwise javascript by default will start updating the results every millisecond which may result in a bad user experience.

Creating functions to check for the state of our input

<script>
  
 //Define the input area in your constructor function
 this.searchField = $(".search-input-class") 
 this.typingTimer //Declare this to enabke us to clear the timeout after eacg keystroke
  
 //Hook the event on the object in your evet area
  this.searchFiel.on("keydown", this.inputFunc.bind(this))
  
  //Declare your function in fnctions area
  function inputFunc() {
    clearTimeput(this.typingTimer)
    this.typingTimer = setTimeout(() => { /*Here you get the results */ }, 1000)
  }
  
</script>

There was a lot of interesting code in here which helps us to complete our advanced search for WordPress let me explain what was done here:

  1. On line 4 we declared an object, which shall be in our constructor function. We declared it there because in your future strps we will need no hook more events on our input fields. And if we parse DOM every time we use it will make our website slow, because in a differnece to DOM java scriot objects and variables are incrediablly fast to run.
  2. On line 5 we have declared typingTimer withiut any value. Then we have assigned value to it on line 13. In order to be able to clear timeout after we have shown the results when the user stoppen typing for a second we need to store it in a variable. This is why we use it.
  3. On line 13 we used set timeout function. The function delays the execution of the code by the given time. It takes two arguments. First id the function that needs to run and the second is the time in milliseconds the function needs to be delayed for.

Search spinner icon

What we have by now is the functionality which has ability to show the results of our posts(the showing functionality is not written yet, we will create it in our next steps). So as soon as the user types what he/she searches for after a second the results shall be showing up.

But in the perioud of a second when the user stopped typing and the result showing up may be fructrating for him/her. To make the website more interactive it is always a good idea to use spinner icon until the contetn shows up. Here is how we shall do it.

<style>
  
//Spinner animation
@-webkit-keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
.spinner-loader {
  margin-top: 45px;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  border: 0.25rem solid rgba(0, 0, 0, 0.2);
  border-top-color: black;
  -webkit-animation: spin 1s infinite linear;
  animation: spin 1s infinite linear;
}
  
</style>

<script>
  
 //Declare an object in constructor 
 this.resultsDiv = $(".search-layout-results")
  
 //Showing spinner icon before showing the text in our inputFunc function
 inputFunc() {
      clearTimeout(this.typingTimer)

      if (this.searchField.val()) {
        if (!this.isSpinnerVisible) {
          this.resultsDiv.html('<div class="spinner-loader"></div>')
          this.isSpinnerVisible = true
        }
        this.typingTimer = setTimeout(this.getResults.bind(this), 2000)
      } else {
        this.resultsDiv.html("")
        this.isSpinnerVisible = false
      }
  }
  
 //Let's get the results
 getSearchResults() {
    this.resultsDiv.html("Imagine real search results here...")
    this.isSpinnerVisible = false
 }
  
</script>

Code explanation:

  1. On the top the code in styles helps to create an element woth spinning animation. Any element containig the class will shoh the animation.
  2. We updated the inputFunc value, first we chech if our input has any value before moving farther. Then before the result showing timeout we check if the soinner is available or no. If it is we show it. Our else instance is the situation when the search result contetn is already seen.

Advanced search for WordPress Conclusion

Our post was too long that is why I devided it into two parts. Here we created all the functionality layout we need to show our search results. In the second post we will parse though the content. Follow the link to continue reading or follow my tutuorial in my Youtube channel.

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.