henrywright
henrywright

Reputation: 10250

AJAX search in WordPress

My aim is to 'ajaxify' WordPress search. So far I have written an AJAX call which passes the user submitted query string to my PHP handler. The parts I'm struggling with are:

1 The PHP handler.

WordPress already has its own PHP search script which I'd like to make use of. How should I integrate this into my PHP handler? Is there an easy way or will I need to rewrite the search script myself?

2 The AJAX response

How should I pass the search results from my PHP handler back to my script? Would I just pass the whole HTML as a string? something like echo json_encode( $html );

I realize my questions are fairly broad so no need for exact code examples. I'm more in need of some high-level ideas as to the approach I should take.

Thanks in advance.

Upvotes: 2

Views: 1947

Answers (2)

Dave Ross
Dave Ross

Reputation: 3491

I'm the author of Dave's WordPress Live Search, so I might be able to help you out a little bit here.

You definitely should familiarize yourself with the preferred way to do AJAX in plugins. This way, your code is flexible enough to work with all the different ways you or someone using your code might want to configure WordPress in the future.

Instead of just using json_encode() to send your response, consider using the new wp_send_json_success and wp_send_json_error functions to include a little extra status information that might come in handy when you're debugging things.

And, lastly, remember my search plugin is MIT licensed, so feel free to dig around in the code and see how I've done things. It's probably a lot more complicated that what you're looking to do, but you might pick up a few pointers from it.

Good luck!

Upvotes: 2

Matthew R.
Matthew R.

Reputation: 4350

Wordpress' search handler is not actually a handler at all. It's part of the WP_Query class. Technically there are some special methods that parse the search string and return relevant results, but you don't have to do anything with those. To use Wordpress to search posts simply add the s argument to the query, like so:

 $args = array(
   'post_type' => 'post',
   'posts_per_page' => -1,
   's' => 'foobar'
 );
 $query = new WP_Query($args);

 return json_encode($query);

Make sure you write your AJAX in a protected function so that people cant submit their own queries on your database. Wordpress will prevent SQL injection, but it's still better safe than sorry.

function SearchConstructor(value){
    function myAjaxCall(){
        $.ajax({
            // Your AJAX Call
        })
        .done(function( msg ) {
            return msg;
        });
    }

    this.get = function(){
        return myAjaxCall.call(this);
    }
};

Here is a better blog post on protecting functions.

Upvotes: 1

Related Questions