wp_json_encode

Encode a variable into JSON, with some sanity checks.

Description

(bool|string) wp_json_encode( (mixed) $data, (int) $options = 0, (int) $depth = 512 ); 

Returns (bool|string)

The JSON encoded string, or false if it cannot be encoded.

Parameters (3)

0. $data (mixed)
Variable (usually an array or object) to encode as JSON.
1. $options — Optional. (int)
Options to be passed to json_encode(). Default 0.
2. $depth — Optional. (int) => 512
Maximum depth to walk through $data. Must be greater than 0. Default 512.

Usage

  1. if ( !function_exists( 'wp_json_encode' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'jetpack-by-wordpress-com/modules/infinite-scroll/infinity.php'; 
  3.  
  4. // Variable (usually an array or object) to encode as JSON. 
  5. $data = null; 
  6.  
  7. // Optional. Options to be passed to json_encode(). Default 0. 
  8. $options = -1; 
  9.  
  10. // Optional. Maximum depth to walk through $data. Must be 
  11. // greater than 0. Default 512. 
  12. $depth = 512; 
  13.  
  14. // NOTICE! Understand what this does before running. 
  15. $result = wp_json_encode($data, $options, $depth); 
  16.  

Defined (1)

The function is defined in the following location(s).

/modules/infinite-scroll/infinity.php  
  1. function wp_json_encode( $data, $options = 0, $depth = 512 ) { 
  2. /** 
  3. * json_encode() has had extra params added over the years. 
  4. * $options was added in 5.3, and $depth in 5.5. 
  5. * We need to make sure we call it with the correct arguments. 
  6. */ 
  7. if ( version_compare( PHP_VERSION, '5.5', '>=' ) ) { 
  8. $args = array( $data, $options, $depth ); 
  9. } elseif ( version_compare( PHP_VERSION, '5.3', '>=' ) ) { 
  10. $args = array( $data, $options ); 
  11. } else { 
  12. $args = array( $data ); 
  13.  
  14. $json = call_user_func_array( 'json_encode', $args ); 
  15.  
  16. // If json_encode() was successful, no need to do more sanity checking. 
  17. // ... unless we're in an old version of PHP, and json_encode() returned 
  18. // a string containing 'null'. Then we need to do more sanity checking. 
  19. if ( false !== $json && ( version_compare( PHP_VERSION, '5.5', '>=' ) || false === strpos( $json, 'null' ) ) ) { 
  20. return $json; 
  21.  
  22. try { 
  23. $args[0] = _wp_json_sanity_check( $data, $depth ); 
  24. } catch ( Exception $e ) { 
  25. return false; 
  26.  
  27. return call_user_func_array( 'json_encode', $args );