I want to use REST API functionality to return JSON data. There are two methods I know of:
- WordPress native REST API implementation: Use WordPress hooks (add_action) to register a custom REST API route (register_rest_route).
- Sage 10 theme, based on Laravel: Use Laravel routes, requiring
ACORN_ENABLE_EXPIRIMENTAL_ROUTER='True'
in the.env
file.
When testing the Laravel routing method, with the following code:
routes/api.php:
Route::get('test/data', function () {
return response()->json(['message' => 'Hello, World!']);
});
.htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
Accessing http://localhost/api/test/data returns:
{"message":"Hello, World!"}<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Page Not Found – Glamoré – Second-hand luxury vintage bags</title>
<meta name='robots' content='noindex, nofollow' />
...
...
Accessing http://localhost/index.php/api/test/data returns:
{"message":"Hello, World!"}
However, there’s a warning in php_error.log:
[Sat Nov 25 01:10:57 2023] PHP Warning: Cannot modify header information - headers already sent by (output started at /Users/wangkairen/Sites/localhost/wp-glamore/wp-content/themes/kieran-craft/vendor/symfony/http-foundation/Response.php:1325) in /Users/wangkairen/Sites/localhost/wp-glamore/wp-includes/pluggable.php on line 1435
[Sat Nov 25 01:10:57 2023] PHP Warning: Cannot modify header information - headers already sent by (output started at /Users/wangkairen/Sites/localhost/wp-glamore/wp-content/themes/kieran-craft/vendor/symfony/http-foundation/Response.php:1325) in /Users/wangkairen/Sites/localhost/wp-glamore/wp-includes/pluggable.php on line 1438
The desired outcome is to have http://localhost/index.php/api/test/data return {“message”:“Hello, World!”}, without PHP header modification warnings. Is this issue related to Acorn’s illuminate/routing limitations? Should I stick to the native WordPress REST API for achieving the desired JSON response?
I’m using WordPress + Sage 10 (v10.7.0) with MAMP PRO, and I encounter the mentioned issue with PHP versions 8.0.2 to 8.2.0.