Let’s say that you want the following JavaScript to run directly in a WordPress post:

document.write('\<ol\>');
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26].forEach(function(x) {
  document.write('\<li\>"' + String.fromCharCode(64 + x) + '" is letter #' + x + ' in the English alphabet.\</li\>');
});
document.write('\</ol\>');

To execute that you can write the following into your post:

<script>
<!--
document.write('\<ol\>');
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26].forEach(function(x) {
  document.write('\<li\>"' + String.fromCharCode(64 + x) + '" is letter #' + x + ' in the English alphabet.\</li\>');
});
document.write('\</ol\>');
//-->
</script>

The resulting of running the above in a WordPress post is this:

As you may have noticed, since I am using document.write(…) to write directly to the document with JS, I am escaping the < and > characters that are used in tag names. They needed to be escaped to allow for WordPress to parse the JS code correctly.

I hope this helps anyone who has been trying to figure out how to properly run raw JavaScript code in a WordPress post. As always, happy coding!!! šŸ˜Ž

Categories: BlogJavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *