
A JSON response in WordPress is the structured data your site sends back after a request most often through the REST API or AJAX. It powers the Block Editor, headless front-ends, mobile apps, and plugins. When responses are valid, editing feels instant; when they’re malformed, you’ll see errors like “Not a valid JSON response.” This guide covers definitions, routes, examples, security, caching, and fixes.
When you update content or fetch data, WordPress returns machine-readable results that scripts can parse quickly. If responses are incorrect, saves fail, previews break, or the editor hangs. A quick way to inspect shape and syntax is to paste the body into a json formatter to see if the structure is valid.
JSON in WordPress
JSON response: The data WordPress returns after an HTTP request, usually a JavaScript-friendly object or array.
Why it matters: The REST API and AJAX rely on JSON to move posts, users, media, and settings without a page reload.
Where JSON comes from in WordPress
REST API (base path:
/wp-json/): Core and custom endpoints expose content and operations.AJAX (
admin-ajax.php): Theme/plugin callbacks return JSON viawp_send_json(),wp_send_json_success(),wp_send_json_error().Custom routes: Register via
register_rest_route(), return withWP_REST_Responseorrest_ensure_response().Block Editor (Gutenberg): Reads/saves content over REST; invalid responses surface as editor errors.
REST API Overview (What, Why, and URL Patterns)
What it is: A web interface that exposes site data and operations as JSON.
Base namespace:
/wp-json/→ core routes live under/wp/v2(e.g., posts, pages, media, users).Common routes:
GET /wp-json/wp/v2/posts?per_page=5→ latest posts (200 OK on success)GET /wp-json/wp/v2/pages/{id}→ single pagePOST /wp-json/wp/v2/posts→ create (needs Authentication/Authorization)
Why JSON: Lightweight, predictable, cacheable, and easy for browsers and apps to parse.
Tip: Keep an eye on Schema for each route knowing expected keys/types avoids client-side surprises.
JSON Response Format (Core Objects & Keys)
Typical fields you’ll see:
Post Object:
id,date,slug,status,title.rendered,content.rendered,excerpt.rendered,author,featured_media,categories,tags,meta,_linksUser Object:
id,name,url,description,avatar_urlsTaxonomy/Term:
id,name,slug,taxonomy,count
Embedding & meta
Add
_embed=1to expand author, featured_media, and terms inline (fewer requests, larger payloads).Meta Fields appear when exposed (via
register_rest_field()or plugin integration).
Inspect, Test, and Validate Responses
Browser DevTools → Network: Open
/wp-json/or/wp-json/wp/v2/posts, review HTTP Response status, headers, and body.cURL (terminal):
curl -i https://example.com/wp-json/wp/v2/posts?per_page=3
Use
--userfor basic tests on protected routes (development only).Postman / Insomnia: Save requests, add Authorization headers (Application Passwords, OAuth, JWT), test Query Parameters and REST Pagination.
WP-CLI + SSH: Reproduce server-side to rule out browser or proxy issues.
Developer Examples
1) Fetch latest posts (front-end)
fetch('/wp-json/wp/v2/posts?per_page=3')
.then(r => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json();
})
.then(data => console.log(data))
.catch(err => console.error(err));
Uses: Fetch API, handles non-200 statuses cleanly.
2) AJAX handler with nonce (theme/plugin)
// functions.php or plugin file
add_action('wp_enqueue_scripts', function () {
wp_enqueue_script('site-ajax', get_stylesheet_directory_uri().'/js/site-ajax.js', ['jquery'], null, true);
wp_localize_script('site-ajax', 'SiteAjax', [
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('site_nonce'),
]);
});add_action(‘wp_ajax_site_example’, ‘site_example_cb’);add_action(‘wp_ajax_nopriv_site_example’, ‘site_example_cb’);
function site_example_cb() {
check_ajax_referer(‘site_nonce’, ‘nonce’);
$items = get_posts([‘numberposts’ => 3]);
wp_send_json_success([‘items’ => $items], 200);
}
// /js/site-ajax.js
jQuery(function ($) {
$('#load-posts').on('click', function(){
$.post(SiteAjax.ajaxurl, { action: 'site_example', nonce: SiteAjax.nonce })
.done(function(res){ console.log(res.data.items); })
.fail(function(){ console.error('Request failed'); });
});
});
Uses: AJAX, Nonce, wp_send_json_success().
3) Custom REST endpoint
add_action('rest_api_init', function () {
register_rest_route('hammani/v1', '/latest', [
'methods' => 'GET',
'callback' => function (\WP_REST_Request $req) {
$limit = min(absint($req->get_param('per_page') ?: 5), 20);
$posts = get_posts(['numberposts' => $limit]);
$payload = array_map(function($p){
return [
'id' => $p->ID,
'title' => get_the_title($p),
'link' => get_permalink($p),
'author' => get_the_author_meta('display_name', $p->post_author),
];
}, $posts);
return new \WP_REST_Response($payload, 200, ['Cache-Control' => 'public, max-age=300']);
},
'permission_callback' => '__return_true',
]);
});
Uses: Custom Endpoint, Permissions Callback, Cache-Control, WP_REST_Response.
Authentication & Authorization
Cookie-based auth: Best for same-origin admin/front-end; pair with Nonce validation.
Application Passwords: Simple, per-user keys for tools and services.
Basic Auth: For local testing only; always over HTTPS.
OAuth / JWT: Token-based REST Authentication for mobile, headless, and third-party API Consumers.
Principle: Grant only what’s needed (role caps, scopes). Map failures to precise Error Codes (401/403).
Security Essentials
Permissions Callback on every sensitive route; never expose private meta by default.
CORS: Allow only trusted origins; enable credentials only when required.
Rate limiting: Throttle anonymous traffic; tighten limits on write routes.
Sanitize & validate:
sanitize_text_field(),absint(), strict parameter checks.Output safety:
wp_kses_post()for allowed markup when serializing rich fields.No extra output: Avoid echoing HTML or PHP notices in JSON paths.
Performance & Caching (Fast, Stable, Scalable)
HTTP caching: Set Cache-Control, ETag, and
Last-Modifiedon GET responses.Server caching: Transients API, Object Cache (Redis/Memcached) for heavy queries.
CDN / reverse proxy: Cache public endpoints at the edge; vary by auth state.
Payload design: Paginate, return minimal fields by default, offer
_embedselectively.Batch & aggregate: Create combined REST Routes to reduce chatty clients.
Troubleshooting “Not a valid JSON response”
Check the actual response body: It should start with
{or[and be parseable; if not, paste into a json formatter to reveal stray markup.Permalinks &
.htaccess: Settings → Permalinks → Save. Restore standard rewrite rules if on Apache.Mixed content / HTTPS: Ensure Site Address and WordPress Address both use HTTPS; fix hard-coded
http://assets.Plugin/theme conflicts: Temporarily switch to a default theme and disable plugins to isolate.
Firewalls/CDNs: Pause or whitelist REST routes (e.g., Cloudflare/Sucuri) if blocked.
Logs & diagnostics: Tools → Site Health (REST section), enable
WP_DEBUG/WP_DEBUG_LOG, review server error logs.Status codes: 401/403 → auth/permission; 404 → wrong route; 500 → server/PHP errors.
Real-World Use Cases
Headless WordPress with React, Vue.js, Next.js, or Gatsby rendering posts from
/wp-json/.Mobile App (iOS/Android) syncing Post Object, User Object, and media over token auth.
Plugin admin UI consuming JSON for dashboards, forms, and reports.
Related reading on HammaniTech:
• How to Create a WordPress Plugin – perfect if you’ll expose a Custom Endpoint.
• WordPress Website Development in 2025: Is It Right for You? – plan your stack around REST capabilities.
• Wix vs Squarespace vs WordPress – platform differences that affect API work.
• How to Migrate a WordPress Site to a New Host – preserve API behavior across environments.
• WordPress Chat Plugin – great example of an API Client inside the admin.
• Browse more tutorials on the HammaniTech Blog.
Working with JSON in PHP
Encoding: Prefer
wp_json_encode()overjson_encode()to inherit sensible defaults and filters (JSON Encoding).Send & exit:
wp_send_json()sets headers and terminates execution; use success/error helpers for standardized shapes.Decoding:
json_decode($json, true)and checkjson_last_error()(JSON Decoding).Errors: Return
WP_Erroror aWP_REST_Responsewith precise status and a machine-readable code.
Tools & Helpful Plugins
Testing: Postman, Insomnia, browser API Console/JSON Viewer.
Expose custom fields: Advanced Custom Fields + ACF to REST API.
Security: JWT/OAuth plugins; hardening via security suites (configure to not block REST).
Alternative API: WPGraphQL if your front-end wants GraphQL instead of REST.
Key Terms
JSON Response – Data WordPress returns/encodes as JSON.
REST API – Interface that provides/exposes JSON routes.
wp-json – Base path that identifies routes.
Endpoint – URL that responds/maps to a resource/action.
Schema – JSON structure that defines/validates fields.
AJAX – Background requests that request/update data.
HTTP Request / HTTP Response – Client sends/retrieves and server delivers data.
200 OK / 404 Not Found / 500 Internal Server Error – Status codes that indicate/signal/report outcomes.
Authentication / Authorization – Identity and permission checks that protect/allow/deny access.
Nonce – Token that validates/prevents forgery in AJAX/REST.
CORS – Cross-origin rules that allow/restrict API access.
Fetch API – Browser method to request/parse JSON.
WP_Query – PHP query class that retrieves/structures data used in responses.
json_encode() / json_decode() – PHP functions to encode/parse JSON.
register_rest_route() / WP_REST_Controller / WP_REST_Request / WP_REST_Response – Core classes/functions that register/process/return/structure routes.
Post/User/Comment/Taxonomy Object – JSON shapes that describe/categorize content.
Meta Fields – Extra keys WordPress stores/returns.
Custom Endpoint – Developer route that creates/exposes curated JSON.
Permissions Callback – Function that verifies/authorizes requests.
wp_send_json() / wp_send_json_success() / wp_send_json_error() – Helpers that output/return/standardize AJAX JSON.
JSONP – Legacy pattern that wraps/loads responses.
Headless WordPress – Use WordPress to decouple/serve JSON to separate front-ends.
React / Vue.js / Next.js / Gatsby – Front-end tools that render/fetch/build from WordPress JSON.
Mobile App – External API Consumer that consumes/syncs JSON.
JSON Error / WP_Error – Standard failures that report/explain issues.
REST Route / Callback Function / REST Namespace – Building blocks that map/run/organize APIs.
wp_localize_script() – Passes JSON settings to scripts.
REST Response Headers / Cache-Control – Metadata that informs/caches clients.
JSON Encoding/Decoding / Serialization/Deserialization – Data transforms that convert/rebuild structures.
REST Authentication / Basic Auth / OAuth / JWT / Application Passwords – Methods that enforce/protect/authenticate/grant/validate/secure access.
Nonce Validation / REST Hooks (
rest_api_init,rest_prepare_post,rest_pre_dispatch) – Extensibility points that initialize/adjust/intercept output.WP_Rest_Server – Core executor that manages REST.
API Client / API Producer – App that fetches/parses vs. server that produces/returns JSON.
REST Pagination / Query Parameters – Tools to limit/narrow results.
JSON Formatting / JSON-LD / Schema.org – Formatting and SEO data that structures/embeds information.
WP_DEBUG / Error Codes / API Schema Validation – Diagnostics that enable/show/validate responses.
rate limiting / JSON middleware / JSON Cache / Transients API / Object Cache / REST Batch Requests / API Versioning / JSON Minification / REST Discovery / API Documentation – Ops and scaling concepts that limit/process/store/group/control/optimize/expose/define APIs.
GraphQL / WPGraphQL – Alternative query layer that queries/provides JSON.
REST Explorer / Postman / Insomnia / API Console / JSON Viewer / JSON Validator / JSON Path – Tools that inspect/test/visualize/validate/query JSON.
API Integration / Webhooks / Push API – Connections that connect/sync/trigger/send updates.
FAQs
What is a JSON response in WordPress?
Data returned by REST or AJAX calls in a compact, predictable format that scripts and apps can parse.
Which routes commonly return JSON?
/wp-json/wp/v2/posts, /pages, /media, /users, plus any Custom Endpoint you register.
How do I register an endpoint?
Hook rest_api_init, call register_rest_route(), return a WP_REST_Response, and enforce a Permissions Callback.
What causes “Not a valid JSON response”?
Mixed content, rewrite issues, plugin/theme output, blocked routes, or PHP errors contaminating output. Use Site Health, logs, and permalinks reset to triage.
How can I speed up JSON endpoints?
Cache with Transients API/Object Cache, add Cache-Control/ETag, paginate, minimize fields, and place public routes behind a CDN.
We use strategic solutions and industry-leading technology to create websites that reflect your brand’s unique identity and grow your customer base and revenue.
