I have an array:
$cats = array('Hobbes', 'Simba', 'Grumpy Cat');
I would like to create a custom endpoint called “http://example.com/cats”. Whenever you visit this URL, have it output the array as JSON:
header('Content-Type: application/json');
$cats = array('Hobbes', 'Simba', 'Grumpy Cat');
echo json_encode($cats);
Ideally creating these on the fly in functions.php. So creating “/dogs” or “/birds”.
6 s
You can use pre_get_posts
as suggested but simply check the global $wp
object for the request url.. like so:
add_action( 'pre_get_posts', function ($query ){
global $wp;
if ( !is_admin() && $query->is_main_query() ) {
if ($wp->request == 'cats'){
header('Content-Type: application/json');
$cats = array('Hobbes', 'Simba', 'Grumpy Cat');
echo json_encode($cats);
exit;
}
}
});
(PHP 5.3+ in this example)
Note 1: The $query->is_main_query()
test is important as it will prevent it from running again in subsequent context of WP_Query instances (eg. if you use a WP_Query to fetch your list of cats, you will end up with an infinite nested loop). is_admin()
isn’t critical but it’s a good practice to use.
Note 2: WordPress seems to trim trailing slashes in request
so this works for /cats
& /cats/
the same way
Note 3: You must exit;
in your handler otherwise it will keep executing the regular wordpress workflow and likely show a 404 page.