13

How To Add Custom JavaScript To WordPress Posts

 4 years ago
source link: https://cwestblog.com/2020/01/31/how-to-add-custom-javascript-to-wordpress-posts/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
How To Add Custom JavaScript To WordPress Posts – Chris West's Blog

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:

  1. "A" is letter #1 in the English alphabet.
  2. "B" is letter #2 in the English alphabet.
  3. "C" is letter #3 in the English alphabet.
  4. "D" is letter #4 in the English alphabet.
  5. "E" is letter #5 in the English alphabet.
  6. "F" is letter #6 in the English alphabet.
  7. "G" is letter #7 in the English alphabet.
  8. "H" is letter #8 in the English alphabet.
  9. "I" is letter #9 in the English alphabet.
  10. "J" is letter #10 in the English alphabet.
  11. "K" is letter #11 in the English alphabet.
  12. "L" is letter #12 in the English alphabet.
  13. "M" is letter #13 in the English alphabet.
  14. "N" is letter #14 in the English alphabet.
  15. "O" is letter #15 in the English alphabet.
  16. "P" is letter #16 in the English alphabet.
  17. "Q" is letter #17 in the English alphabet.
  18. "R" is letter #18 in the English alphabet.
  19. "S" is letter #19 in the English alphabet.
  20. "T" is letter #20 in the English alphabet.
  21. "U" is letter #21 in the English alphabet.
  22. "V" is letter #22 in the English alphabet.
  23. "W" is letter #23 in the English alphabet.
  24. "X" is letter #24 in the English alphabet.
  25. "Y" is letter #25 in the English alphabet.
  26. "Z" is letter #26 in the English alphabet.

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!!! 😎


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK