将变量编码为JSON,并进行一些健全性检查。

原型

wp_json_encode( mixed $data, int $options, int $depth = 512 )

参数

$data (mixed) (Required) 变量(通常是数组或对象),以编码为JSON。

$options (int) (Optional)  要传递给json_encode()的选项。默认值为0。

$depth (int) (Optional)  遍历$ data的最大深度。必须大于0。

返回值

(string|false)  JSON编码的字符串,如果无法编码,则为false。

源文件

路径:wp-includes/functions.php

<?php
...
function wp_json_encode( $data, $options = 0, $depth = 512 ) {
	/*
	 * json_encode() has had extra params added over the years.
	 * $options was added in 5.3, and $depth in 5.5.
	 * We need to make sure we call it with the correct arguments.
	 */
	if ( version_compare( PHP_VERSION, '5.5', '>=' ) ) {
		$args = array( $data, $options, $depth );
	} elseif ( version_compare( PHP_VERSION, '5.3', '>=' ) ) {
		$args = array( $data, $options );
	} else {
		$args = array( $data );
	}
	// Prepare the data for JSON serialization.
	$args[0] = _wp_json_prepare_data( $data );
	$json = @call_user_func_array( 'json_encode', $args );
	// If json_encode() was successful, no need to do more sanity checking.
	// ... unless we're in an old version of PHP, and json_encode() returned
	// a string containing 'null'. Then we need to do more sanity checking.
	if ( false !== $json && ( version_compare( PHP_VERSION, '5.5', '>=' ) || false === strpos( $json, 'null' ) ) )  {
		return $json;
	}
	try {
		$args[0] = _wp_json_sanity_check( $data, $depth );
	} catch ( Exception $e ) {
		return false;
	}
	return call_user_func_array( 'json_encode', $args );
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/wp_json_encode/