Support » Developing with WordPress » Ampersands Being Escaped in HTML Block

  • Resolved CrouchingBruin


    I added some Javascript code to a post using an HTML block. For some reason, some of the ampersands are being escaped.
    Original code:

    if(mx < $(this).width() && my < $(this).height() && mx > 0 && my > 0)

    Saved code:

    if(mx < $(this).width() &#038;&#038; my < $(this).height() &#038;&#038; mx > 0 && my > 0)

    As you can see, the first and second set of double ampersands gets escaped, but the third does not, which is really weird. If you do a view source on the example page, you can find this line of code at line 180. I even tried copying & pasting the third pair of ampersands over the first and second, just in case there was some sort of hidden encoding that I couldn’t see. Earlier, at line 154, there’s another double ampersand that correctly doesn’t get escaped.

    I’m puzzled as to why anything in an HTML block would get escaped. Isn’t everything in an HTML block supposed to be retained “as is?”

    The page I need help with: [log in to see the link]

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz


    Post content is passed through esc_html() because not doing so makes it possible for a malicious script to execute. It’s a safety mechanism. In any case, because of this an a few other things WP does with content, it’s infeasible to place script directly into post content. It will get corrupted.

    If you want to insert script and keep it uncorrupted, you need to use a shortcode or custom block.

    OK, thanks, I’ll just move the script to a plugin that does JS injections in the header. Kind of odd, though, that the escaping is very inconsistent. None of the other ampersands got escaped, nor did any of the lesser than or greater than signs, which, according to the Data Validation codex, under esc_html(), are all supposed to be escaped as well.



    OK, I found an answer in the WordPress Codex that works. All I had to do was add the HTML comment tags right after the begin <script> tag and before the end </script> script tag, and the ampersands didn’t get escaped:

    <script type="text/javascript">
Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.