* Thin jQuery.ajax wrapper for WP REST API requests.
* Currently only applies to requests that do not use the `wp-api.js` Backbone
* client library, though this may change. Serves several purposes:
* - Allows overriding these requests as needed by customized WP installations.
* - Sends the REST API nonce as a request header.
* - Allows specifying only an endpoint namespace/path instead of a full URL.
* @since 5.6.0 Added overriding of the "PUT" and "DELETE" methods with "POST".
* Added an "application/json" Accept header to all requests.
* @output wp-includes/js/api-request.js
var wpApiSettings = window.wpApiSettings;
function apiRequest( options ) {
options = apiRequest.buildAjaxOptions( options );
return apiRequest.transport( options );
apiRequest.buildAjaxOptions = function( options ) {
var method = options.method;
var namespaceTrimmed, endpointTrimmed, apiRoot;
var headers, addNonceHeader, addAcceptHeader, headerName;
typeof options.namespace === 'string' &&
typeof options.endpoint === 'string'
namespaceTrimmed = options.namespace.replace( /^\/|\/$/g, '' );
endpointTrimmed = options.endpoint.replace( /^\//, '' );
path = namespaceTrimmed + '/' + endpointTrimmed;
if ( typeof path === 'string' ) {
apiRoot = wpApiSettings.root;
path = path.replace( /^\//, '' );
// API root may already include query parameter prefix
// if site is configured to use plain permalinks.
if ( 'string' === typeof apiRoot && -1 !== apiRoot.indexOf( '?' ) ) {
path = path.replace( '?', '&' );
// If ?_wpnonce=... is present, no need to add a nonce header.
addNonceHeader = ! ( options.data && options.data._wpnonce );
headers = options.headers || {};
for ( headerName in headers ) {
if ( ! headers.hasOwnProperty( headerName ) ) {
// If an 'X-WP-Nonce' or 'Accept' header (or any case-insensitive variation
// thereof) was specified, no need to add the header again.
switch ( headerName.toLowerCase() ) {
// Do not mutate the original headers object, if any.
'X-WP-Nonce': wpApiSettings.nonce
'Accept': 'application/json, */*;q=0.1'
if ( typeof method === 'string' ) {
method = method.toUpperCase();
if ( 'PUT' === method || 'DELETE' === method ) {
'X-HTTP-Method-Override': method
// Do not mutate the original options object.
options = $.extend( {}, options, {
delete options.namespace;
apiRequest.transport = $.ajax;
window.wp = window.wp || {};
window.wp.apiRequest = apiRequest;