_wp_json_prepare_data
Prepares response data to be serialized to JSON.
Description
(bool|int|float|null|string|array) _wp_json_prepare_data( (mixed) $data );
This supports the JsonSerializable interface for PHP 5.2-5.3 as well.
Returns (bool|int|float|null|string|array)
Data ready for `json_encode()`.
Parameters (1)
- 0. $data (mixed)
- Native representation.
Usage
if ( !function_exists( '_wp_json_prepare_data' ) ) { require_once ABSPATH . WPINC . '/functions.php'; } // Native representation. $data = null; // NOTICE! Understand what this does before running. $result = _wp_json_prepare_data($data);
Defined (1)
The function is defined in the following location(s).
- /wp-includes/functions.php
- function _wp_json_prepare_data( $data ) {
- if ( ! defined( 'WP_JSON_SERIALIZE_COMPATIBLE' ) || WP_JSON_SERIALIZE_COMPATIBLE === false ) {
- return $data;
- }
- switch ( gettype( $data ) ) {
- case 'boolean':
- case 'integer':
- case 'double':
- case 'string':
- case 'NULL':
- // These values can be passed through.
- return $data;
- case 'array':
- // Arrays must be mapped in case they also return objects.
- return array_map( '_wp_json_prepare_data', $data );
- case 'object':
- // If this is an incomplete object (__PHP_Incomplete_Class), bail.
- if ( ! is_object( $data ) ) {
- return null;
- }
- if ( $data instanceof JsonSerializable ) {
- $data = $data->jsonSerialize();
- } else {
- $data = get_object_vars( $data );
- }
- // Now, pass the array (or whatever was returned from jsonSerialize through).
- return _wp_json_prepare_data( $data );
- default:
- return null;
- }
- }