Alex Kibler
Alex Kibler

Reputation: 4954

How to create an API endpoint within Wordpress?

I'm working on my first wordpress project (I develop in .NET and Angular normally), and I've hit a bit of a snag. I've got a requirement to make a search box that has typeahead functionality. I want to be able to send the search query to an internal API as the user types. I know I can use a jQuery plugin for the front-end part of this, but having never worked in PHP before, I don't know how to create the endpoint to accept the query and return the results. Is this even possible? I've been searching for it, but I can't find any articles about adding APIs in wordpress.

Upvotes: 1

Views: 64

Answers (1)

Jeremy Hamm
Jeremy Hamm

Reputation: 499

There are a few ways to go about it. It depends on how robust your API solution needs to be. The Slim Router is a good easy to implement php api solution.

$app = new \Slim\App();
$app->get('/books/{id}', function ($request, $response, $args) {
    // Show book identified by $args['id']
});

The quick way to do this would be to point your ajax call to a standalone php page which would take the query params, query the DB and return the results.

// Read query params $param = $_GET['param'];
// Interact with DB
// echo json_encode() Encode and echo output

Upvotes: 1

Related Questions