wppaste
WordPress

wp_json_encode( mixed $value, int $flags = 0, int $depth = 512 ): string|false

Since
4.1.0, 5.3.0, 6.5.0
Source
wp-includes/functions.php:4443

Serializes PHP data into a JSON string using json_encode(), then retries with a UTF-8 sanity check if the first pass fails. Useful for building AJAX payloads or inline script data from post arrays, objects, or associative arrays. Returns false, not an empty string, when encoding cannot succeed even after the retry, so check the return value with a strict comparison rather than truthiness.

Encodes a variable into JSON, with some confidence checks.

Compatibility

WordPress
since 6.5.0
PHP
7.4–8.6-dev
  • 6.7.7
  • 6.8.8
  • 6.9.7
  • 7.0.4
  • 7.1.0

Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.

Parameters

$valuemixed
Variable (usually an array or object) to encode as JSON.
$flagsintoptional
Options to be passed to json_encode(). Default 0.Default: 0
$depthintoptional
Maximum depth to walk through $value. Must be greater than 0. Default 512.Default: 512

Return value

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

Code examples

Every example is editable and runs in a real WordPress booted in your browser by WordPress Playground. Press Run, then edit the code: clicking away re-runs it. Nothing is sent anywhere until you do.

Encode a post's fields as JSON for an admin-ajax response

Build a small array from an existing post and its meta, then encode it for output.

$post = get_post( 2 );

$payload = array(
	'id'    => $post->ID,
	'title' => $post->post_title,
	'price' => get_post_meta( $post->ID, 'price', true ),
);

$json = wp_json_encode( $payload );

if ( false === $json ) {
	echo 'Could not encode payload.';
} else {
	echo esc_html( $json );
}

Pretty-print a nested array of post titles for debugging

Pass the JSON_PRETTY_PRINT flag so the encoded output is readable when printed to the page.

$titles = array();

foreach ( array( 1, 2, 3 ) as $post_id ) {
	$titles[] = get_the_title( $post_id );
}

$json = wp_json_encode( array( 'titles' => $titles ), JSON_PRETTY_PRINT );

echo '<pre>' . esc_html( $json ) . '</pre>';

JSON_PRETTY_PRINT is passed straight through to json_encode() as the $flags argument.

Common problems and fixes · 4

Why does wp_json_encode return false for an array that looks fine?

json_encode() fails outright when a string in the data is not valid UTF-8, and that failure is what triggers the fallback in wp_json_encode(). The fallback calls _wp_json_sanity_check() to try to fix the encoding, but if that throws an exception the function gives up and returns false.

What does wp_json_encode do differently from plain json_encode?

The source calls json_encode() first and returns immediately if it succeeds, so in the common case there is no behavior difference at all.

How do I stop deeply nested data from breaking the JSON output?

Both json_encode() and wp_json_encode() cap how many levels of nesting they will walk through the $depth parameter, which defaults to 512 here just as it does in json_encode().

Is it safe to echo the result of wp_json_encode directly into an HTML attribute?

wp_json_encode() only produces a JSON string, it does not escape it for the context you print it into, so unescaped output next to attribute quotes can break markup.

Alternatives and related functions

json_encode
When you are outside the WordPress bootstrap or don't need the UTF-8 sanity-check fallback that wp_json_encode adds.
wp_send_json
When the encoded value is the entire body of an admin-ajax or REST response, since it also sets the Content-Type header and ends the request.
wp_send_json_success
When you're returning a successful AJAX result and want the standard success wrapper instead of hand-building the array.
json_decode
When you need to turn a JSON string back into a PHP array or object rather than encode one.

Performance profile

How much work a call to wp_json_encode() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.

Cost class
Trivial

Touches nothing outside its own arguments.

Scaling
Constant

No loop in the body: the same number of instructions runs whatever you pass in.

Instructions
12–23

Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 26.

Plugin surface
None

Nothing here hands control to plugin code.

Called by
50

50 places in core call this, so the cost is paid more often than your own code shows.

What it touches

  • serializeserialisationjson_encode()called directly

Further down the call graph this can also reach option, hook, cache, query and transient. Those are the worst case, several calls deep and usually down an error path, not what a normal call pays.

What one call costs · 2 distinct outcomes

One number would be a lie: the work depends on which branch runs. These are every distinct cost wp_json_encode() can have, taken from its control-flow graph on PHP 8.5.

WhenInstructionsCalls it makes
$json !== false12json_encode()
$json === false23json_encode(), _wp_json_sanity_check(), json_encode()

Across PHP versions

Compiles the same on PHP 7.4, 8.1, 8.2, 8.3, 8.4, 8.5 and 8.6-dev: 26 instructions, 12–23 executed per call, 1 branch. The work does not change between versions.

An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.

Uses · 1

Used by · 50

Show all 50

Source code

function wp_json_encode( $value, $flags = 0, $depth = 512 ) {	$json = json_encode( $value, $flags, $depth ); 	// If json_encode() was successful, no need to do more confidence checking.	if ( false !== $json ) {		return $json;	} 	try {		$value = _wp_json_sanity_check( $value, $depth );	} catch ( Exception $e ) {		return false;	} 	return json_encode( $value, $flags, $depth );}

Changelog

Introduced in 4.1.0. Unchanged from 6.7.7 through 7.1.0.

  1. 6.7.7
  2. 6.8.8
  3. 6.9.7
  4. 7.0.4
  5. 7.1.0

Signature, return type and hooks compared across 5 parsed releases.

6.5.0
The $data parameter has been renamed to $value and the $options parameter to $flags for parity with PHP.from the docblock
5.3.0
No longer handles support for PHP < 5.6.from the docblock
4.1.0
Introduced.from the docblock

About this page

Parsed data
Generated from the wordpress-develop 7.1.0 tag, from src/wp-includes/functions.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it.
Corrections
Something wrong on this page? Report it and it gets fixed in the next regeneration.