WordPress.org

Make WordPress Core

Ticket #35666: 35666.diff

File 35666.diff, 2.2 KB (added by stephenharris, 6 years ago)

Adds support for a 'status_code' parameter to wp_send_json(_error|_success)

  • src/wp-includes/functions.php

    diff --git src/wp-includes/functions.php src/wp-includes/functions.php
    index 0e720ee..a88e9bd 100644
    function _wp_json_prepare_data( $data ) { 
    30313031 * Send a JSON response back to an Ajax request.
    30323032 *
    30333033 * @since 3.5.0
     3034 * @since 4.6.0 If provided, sets the header status to `$response['status_code']`
    30343035 *
    30353036 * @param mixed $response Variable (usually an array or object) to encode as JSON,
    30363037 *                        then print and die.
    30373038 */
    30383039function wp_send_json( $response ) {
    30393040        @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
     3041        if ( isset( $response['status_code'] ) ) {
     3042                status_header( (int) $response['status_code'] );
     3043                unset( $response['status_code'] );
     3044        }
    30403045        echo wp_json_encode( $response );
    30413046        if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
    30423047                wp_die();
    function wp_send_json( $response ) { 
    30483053 * Send a JSON response back to an Ajax request, indicating success.
    30493054 *
    30503055 * @since 3.5.0
     3056 * @since 4.6.0 The `$status_code` parameter was added
    30513057 *
    30523058 * @param mixed $data Data to encode as JSON, then print and die.
    30533059 */
    3054 function wp_send_json_success( $data = null ) {
    3055         $response = array( 'success' => true );
     3060function wp_send_json_success( $data = null, $status_code = 200 ) {
     3061        $response = array( 'success' => true, 'status_code' => (int) $status_code );
    30563062
    30573063        if ( isset( $data ) )
    30583064                $response['data'] = $data;
    function wp_send_json_success( $data = null ) { 
    30713077 * @since 3.5.0
    30723078 * @since 4.1.0 The `$data` parameter is now processed if a {@see WP_Error}
    30733079 *              object is passed in.
     3080 * @since 4.6.0 The `$status_code` parameter was added
    30743081 *
    3075  * @param mixed $data Data to encode as JSON, then print and die.
     3082 * @param mixed $data        Data to encode as JSON, then print and die.
     3083 * @param int   $status_code HTTP status code.
    30763084 */
    3077 function wp_send_json_error( $data = null ) {
    3078         $response = array( 'success' => false );
     3085function wp_send_json_error( $data = null, $status_code = 200 ) {
     3086        $response = array( 'success' => false, 'status_code' => (int) $status_code );
    30793087
    30803088        if ( isset( $data ) ) {
    30813089                if ( is_wp_error( $data ) ) {