Reputation: 946
I'm using building out a section of a Wordpress site that uses an API built on top of an older database that needs to remain in tact. The API is really simple and will be accessed only in two ways:
mysite.com/monkeys/ <-- This corresponds to calling the API as '/api/monkeys/list'
mysite.com/monkey/william <-- Calling the API as '/api/monkeys/:name'
Because the data from the API is controlled by a 3rd party and does not need to be managed by Wordpress, I'm wondering how best I can build this out so that Wordpress doesn't throw 404s/redirect when I try to hit these urls.
Furthermore, if I decide to cache these calls (the API is clunky and slow) how might I integrate them into a Wordpress search?
Please let me know if I can clarify anything - thanks!
Upvotes: 1
Views: 938
Reputation: 26055
You can add an endpoint. The following example only detects endpoints on the root (EP_ROOT
). If we visit example.com/monkeys/
it's considered your /api/monkeys/list
. And when visiting example.com/monkeys/name
it's your /api/monkeys/:name
.
If you really want to separate a monkey from the band, add another endpoint.
add_action( 'init', function()
{
add_rewrite_endpoint( 'monkeys', EP_ROOT );
});
add_filter( 'query_vars', function( $vars )
{
$vars[] = 'monkeys';
return $vars;
});
This code requires refreshing the permalinks manually in Settings >> Permalinks >> Save
, but it can be auto refreshed on plugin activation.
To test the endpoint, I used this:
add_action( 'wp_footer', function(){
// set default as 'empty', so we can differentiate the root from no query var
$monkeys = get_query_var( 'monkeys','empty' );
if( 'empty' === $monkeys ) {
printf( '<h1 style="font-size:4em">%s</h1>', 'NOT SET' );
}
else if( '' === $monkeys ) {
printf( '<h1 style="font-size:4em">%s</h1>', 'Endpoint root.' );
}
else {
printf( '<h1 style="font-size:4em">Sent query: %s</h1>', urldecode( $monkeys ) );
}
});
Upvotes: 2
Reputation: 2300
Why don't you just create those resources ... they won't be 404 then ...
We've used this approach successfully on OMBE; we simply created scripts (in your case they'd be "monkey" and "monkeys") which are wrappers for something else (like the API in your case) and used an Apache ForceType directive (pointing to application/x-httpd-php5) to handle them.
HTH,
Upvotes: 0