From 2e7e09d869d92a3ea17077fc3692578e27b09b57 Mon Sep 17 00:00:00 2001 From: Felix Arntz Date: Wed, 16 Jan 2019 15:22:56 +0000 Subject: [PATCH] Bootstrap/Load: Add support for JSON requests to `wp_die()`. In addition to AJAX and XML-RPC requests, `wp_die()` now handles JSON requests correctly, returning information in the expected content type. Props spacedmonkey. See #45933, #44458. Built from https://develop.svn.wordpress.org/trunk@44625 git-svn-id: http://core.svn.wordpress.org/trunk@44456 1a063a9b-81f0-0310-95a4-ce76da25c4cd --- wp-includes/functions.php | 43 +++++++++++++++++++++++++++++++++++++++ wp-includes/version.php | 2 +- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/wp-includes/functions.php b/wp-includes/functions.php index 36b59ac8e1..ca91c53e00 100644 --- a/wp-includes/functions.php +++ b/wp-includes/functions.php @@ -2975,6 +2975,15 @@ function wp_die( $message = '', $title = '', $args = array() ) { * @param callable $function Callback function name. */ $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' ); + } elseif ( wp_is_json_request() ) { + /** + * Filters the callback for killing WordPress execution for JSON requests. + * + * @since 5.1.0 + * + * @param callable $function Callback function name. + */ + $function = apply_filters( 'wp_die_json_handler', '_json_wp_die_handler' ); } elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) { /** * Filters the callback for killing WordPress execution for XML-RPC requests. @@ -3215,6 +3224,40 @@ function _default_wp_die_handler( $message, $title = '', $args = array() ) { die(); } +/** + * Kill WordPress execution and display JSON message with error message. + * + * This is the handler for wp_die when processing JSON requests. + * + * @since 5.1.0 + * @access private + * + * @param string $message Error message. + * @param string $title Optional. Error title. Default empty. + * @param string|array $args Optional. Arguments to control behavior. Default empty array. + */ +function _json_wp_die_handler( $message, $title = '', $args = array() ) { + $defaults = array( 'response' => 500 ); + + $r = wp_parse_args( $args, $defaults ); + + $data = array( + 'code' => 'wp_die', + 'message' => $message, + 'status' => $r['response'], + ); + + if ( ! headers_sent() ) { + header( 'Content-Type: application/json; charset=utf-8' ); + if ( null !== $r['response'] ) { + status_header( $r['response'] ); + } + } + + echo wp_json_encode( $data ); + die(); +} + /** * Kill WordPress execution and display XML message with error message. * diff --git a/wp-includes/version.php b/wp-includes/version.php index 01d9a2f04e..1c2a84bb67 100644 --- a/wp-includes/version.php +++ b/wp-includes/version.php @@ -13,7 +13,7 @@ * * @global string $wp_version */ -$wp_version = '5.1-beta1-44624'; +$wp_version = '5.1-beta1-44625'; /** * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.