[wp-trac] [WordPress Trac] #51159: Let's expand our context specific escaping methods for wp_json_encode().

WordPress Trac noreply at wordpress.org
Wed Aug 13 11:41:15 UTC 2025


#51159: Let's expand our context specific escaping methods for wp_json_encode().
-------------------------+-------------------------------------------------
 Reporter:  whyisjake    |       Owner:  (none)
     Type:  enhancement  |      Status:  new
 Priority:  normal       |   Milestone:  Awaiting Review
Component:  Security     |     Version:
 Severity:  normal       |  Resolution:
 Keywords:               |     Focuses:  javascript, template, coding-
                         |  standards
-------------------------+-------------------------------------------------

Comment (by jonsurrell):

 I agree with the spirit of this ticket. It recognizes that **there is no
 one-size-fits-all HTML escaping**. Appropriate escaping is contextual and
 complicated.

 > All of this dovetails nicely with the goals of the HTML API…

 I also have high hopes for what the HTML API can provide here.
 Transitioning more things to rely on the HTML API should help to fix
 things.

 Script tags, however, are particularly difficult and I still believe that
 properly escaped JSON is beneficial before handing this off to the HTML
 API.

 Specific, contextual functions like `wp_json_encode_for_script_tag()`
 could help the problem by using the appropriate JSON flags for the
 context. However, I'm not convinced by the solution because it needs to be
 discovered and then applied appropriately.

 An alternative could be a combination of:

 - Improved messaging and recommendations with `_doing_it_wrong` in various
 places.
 - There are possibilities for escaping that can be applied to JavaScript
 in general. This could be applied by the HTML API and different core
 functionality could rely on it. I have ideas and explorations in this
 direction I hope to prepare and propose soon.

 > PHP’s `json_encode()` has an `$options` parameter, which can be used to
 always Unicode-escape these HTML special characters [with] `JSON_HEX_TAG |
 JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT` [in script tags].

 This recommendation is sound, although it's excessive. It escapes
 characters which do not need to be escaped and leaves redundant escaping.
 I recommend `JSON_HEX_TAG | JSON_UNESCAPED_SLASHES`.
 [https://sirre.al/2025/08/06/safe-json-in-script-tags-how-not-to-
 break-a-site/ I wrote in detail about this for folks that may be
 interested.]

 #62797 is an example of an issue the manifests when JSON in `script` tags
 is not correctly escaped.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/51159#comment:3>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list