Search code examples
javascriptjqueryajaxwordpress-rest-api

How to use search box to filter posts from WordPress API?


I have been able to get a list of posts on a php web page (outside of WordPress). How can I use the search box to filter the existing results by blog title(search term).

Here is my search box


    <div class="sbox">
            <h4>Search blog by title</h4>
              <div class="form-group ">
                <input type="text" name="search_box" id="search_box" class="form-control" placeholder="Search by title, author or category" >
              </div>
            </div>

Here is my ajax attempt


    $('#search_box').keyup(function(){
          var text = $('#search_box').val();
          var api_url_search = `http://example.com/wordpress/wp-json/wp/v2/posts?filter[s]=${text}`;

           $.ajax({
            url:api_url_search,
           dataType: 'json',
                success: function(response){
                   var len = response.length;
                    for(var i=0; i<len; i++){
                        var title = response[i].title.rendered;
                        var search_str =
                         '<li>'+                     
                         '<p>' + title + '</p>' +                    
                           '</li>'           
                            ; 
              $('#results').append(search_str);
            }
                }
          });
        });

It seems to be looping through every letter that is typed and returning all posts for each letter.


Solution

  • I found the answer. The WordPress api won't enable you to filter by title but you can filter by slug. So the user has to type the title with hyphens (e.g my-title)

    
        //setup before functions
        var typingTimer;                //timer identifier
        var doneTypingInterval = 5000;  //time in ms (5 seconds)
    
    
    
        //on keyup, start the countdown
        $('#search_box').keyup(function(){
            clearTimeout(typingTimer);
            if ($('#search_box').val()) {  
              var text = $('#search_box').val();    
                typingTimer = setTimeout(doneTyping(text), doneTypingInterval)
            }
        });
    
        //user is "finished typing," do something
        function doneTyping (text) {
    
    
            // var text = text;
    
              var api_url_search = `http://examle.com/wordpress/wp-json/wp/v2/posts?slug=${text}`;
    
               $.ajax({
                url:api_url_search,
               dataType: 'json',
                    success: function(response){
                         var len = response.length;                     
        for(var i=0; i<len; i++){
                            var id = response[i].id;
                            var date = response[i].date_gmt;
                            var slug = response[i].slug;
                            var excerpt = response[i].excerpt.rendered;
                            var categories = response[i].categories;
    
                            var search_str =
                             '<td>'+
                            '<div class="card" style="width: 300px;">' +
                             '<div class="card-divider">' + (i+1) + ' ' + slug + '</div>' +    
    
                            ' <div class="card-section">' +   
                             '<p>' + excerpt + '</p>' +
                             '<h4>' +  date + '</h4>' +
                             '<h4>' + 'Category:' + categories + '</h4>' +
                            '<a href="http://example.com/api-posts.php?">'+ 
                            '<input type="button" value="read more">' + '</input>' +
                            ' </a>' +
                            ' </div>' +
                             '</div>'+
                               '</td>'           
                                ;
    
                 $('#results').empty().append(search_str); // empty previous results and append new results
         } 
                    }
         });
         };