Apr 192014
 

Add JavaScript to WordPress Post or Page tutorial teaches you how to add JavaScript and other codes to WordPress post and pages.

Last Updated: August 7, 2018

Revision Update: I have updated the information below.

This tutorial was written using the following plugin TinyMCE Advanced.

I have now tested this tutorial adding JavaScript and other codes using WordPress 4.9.8.

The browsers tested:

  1. IE 11
  2. FireFox
  3. Google Chrome
  4. Seamonkey
  5. Microsoft Edge

Note: Always have the latest version of the browser installed. Make sure you clear your cache regularly. Make sure Java is always up to date.

Important: When adding JavaScript to your posts or pages, if you change between the Text and Visual editor you might loose the code or tags and or funny characters might appear. This could be due to a conflict with another plugin using JavaScript or your with your theme.

As a golden rule, for better performance and control you should really be adding JavaScript code to you the following theme files header.php, footer.php or custom.php. This would also allow you to use shortcodes in your pages or posts to call the custom script added. If you are going to be customizing your theme then it is best to use a child theme.

Add JavaScript to WordPress Post or Page

Step 1 ) The following images shows you a very simple JavaScript code added to a post.

  • document.write = which will write the text to your post. The text that it will write is Hello World!.

Always edit or add the code using the Text editor. See image below.

add-javascript-to-wordpress-html-editor-text

In the following image you can see the javascript code added.

add-javascript-to-wordpress-html-editor-new

Step 2 ) The following image displays what you will see if you select the Visual editor. This is what you typed in the Text editor. This time you have switched to the Visual editor to see the outcome of your code. You can see that the javascript code is not displayed.

add-javascript-to-wordpress-visual-editor

Step 3 ) The following image you have switched back to the Text  editor. This time you will notice some code added by WordPress, // <![CDATA[ at the beginning of the script and // ]]> at the end of the script.

Note: You can read more about this by clicking in the following URL Wikipedia CDATA.

add-javascript-to-wordpress-code-changed

Step 4 ) The following image shows you the end result viewed from the front of your website. You can see Hello World!. That is how simple it is to add some javascript code.

add-javascript-to-wordpress-final-result

Add iframe To WordPress Post or Page

Step 5 ) Copy and paste the iframe code you selected to your post or page through the Text editor by clicking on HTML tab. The editor will place the iframe in between < p > < /p > tag. See image below.

 add javascript to wordpress

Using TinyMCE Advanced Plugin.

Step 6 ) The following instructions are for those who want to use a plugin to add an iframe. Select the following icon and add your code, url and other settings you prefer. See images below.

Remember: Check the following URL WordPress TinyMCE Advanced Plugin Settings to learn more about TinyMCE Advanced plugin.

Step 6-a ) Go to Insert -> Media as illustrated in the following image to insert an iframe.

add-javascript-wordpress-ultimate-tinymce-insert-icon

Insert/edit media

Step 6-b ) The following image General tab allows you to set up the following options.

General Tab

  • Source
  • Dimensions = choose whether you want to enable Constrain proportions or not.

add-javascript-wordpress-ultimate-tinymce-add-scripts

Step 6-c ) The following image Embed tab allows you to paste the source code.

Embed Tab

  • Paste your embed code below.

add-javascript-wordpress-ultimate-tinymce-embed-source

Step 6-d ) The following image Advanced allows you to set up the following options.

Advanced Tab

  • Alternative source
  • Poster
  • Click on Ok button when you are finished.

add-javascript-wordpress-ultimate-tinymce-add-scripts-advanced

Javascript Plugins I Recommend

  • Insert Html Snippet Allows you to add HTML, CSS and javascript code to your pages and posts easily using shortcodes.
  • RawHtml Allows you to insert raw HTML or other codes in your posts and pages. You can also disable smart quotes and other automatic formatting on a per-post basis.

In regards to Raw HTML, there are two versions available Free and Pro. The free version only works with the HTML editor, it is not compatible with Visual editor. To use with Visual editor you need to purchase the Pro version.

Note: Always create a backup before you try any new plugin just in case something happens.

I hope this helps you and puts you on the right track. If you need any help just leave a comment or send me an e-mail.

Come back for more information as I keep updating this post.

Enjoy.

I have been working in IT since 1999 and I enjoy the challenges it brings me. I love developing websites with WordPress. I spend a lot of time helping out in wordpress.org forums. I have been writing tutorials since 2011. Now I am learning how to manage my own VPS "Virtual Private Server.

  30 Responses to “Add Javascript to WordPress Post or Page”

  1. I tried the above adding the p tag and the   and it did not work. I will try the plugins and see what happens.

    Thanks,
    -Geej Mauriva

    • Hello Geej, it is very challenging to get it work properly. Remember that if you have TinyMce Advance plugin installed try to disable it and see if it works. Also they have released an update for TinyMce Advance plugin. I have not tested the update yet. The plugins I mention will work, I have done some testing with the plugins and they work very well.

      Kind regards

  2. Please write more article as you are a great writer. I am so happy reading your work because it is so informative and full of ideas. Write and write because you have the potential.

  3. I want to insert some code like this, but it failed!

    var ARRcookies=document.cookie.split(";");
    if( ARRcookies.length == 0 )
    document.writeln("No cookie found.");
    else{
    document.writeln("");
    for (var i=0;i<ARRcookies.length;i++){
    var x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
    var y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
    x=x.replace(/^s+|s+$/g,"");
    document.writeln(""+x+""+y+"");
    }
    document.writeln("");
    }


    Wordpress changes it to:

    // <![CDATA[
    var ARRcookies=document.cookie.split(";");
    if( ARRcookies.length == 0 )
    document.writeln("No cookie found.");
    else{
    document.writeln("
    ");
    for (var i=0;i<ARRcookies.length;i++){
    var x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
    var y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
    x=x.replace(/^s+|s+$/g,"");
    document.writeln("
    "+x+"
    "+y+"
    ");
    }
    document.writeln("
    ");
    }
    // ]]>

    And this cannot run.

    • Hi gameletjapplet, thank you for your question. If you are going to insert a javascript code into WordPress you need to enclose the code with a html tag as follow:

      < script>
      alert ("My First JavaScript") ;
      < /script>

      Remember to remove the spaces I have added so the code could be displayed and not run

      If you don’t use tags then the code will not work. The other method is to create a .js file and upload to the page via the following method.

      < script src="myScript.js">< /script>

      I hope this helps you.

      Kind regards

      • Event I add to my page, it’s still not working.

        • Hello Xiu, thank you for your question. Can you provide more details so that I can work out what is happening and why you can’t add it to your page.

          Kind regards

      • Well, I had already added tag. I just didn’t show it in my comment. Simply put, even I add it to my page, it’s still not working.

        • Hi, are you inserting the code in a page or post? What version of WordPress are you running? Try an install TinyMCE Advanced plugin. Have you tried to install any of the two plugins mentioned in my tutorial?

  4. Hey there!
    Thank you for your wonderful tutorial.
    I have the same issue – i can’t get the javascript to work.

    I have an external gallery.js-file with this code:

    function swap(image) {
    document.getElementById("main").src = image.href;
    }

    In my post, I call the script with these lines:

    Directly after, I insert my gallery with images from my swap gallery:

    I’m using WordPress Version 3.5 and have no text-plugins installed.
    Can you tell me where I make a mistake? I’m so frustrated >.<

    Thank you very much!
    Christina
    I'm looking arou

    • Hello Christina, thank you for your question. I am sorry to hear you are having problems with your code. Can you please add the code using < pre>< /pre> html tangs please because unfortunately your code did not show up.

      Kind regards

  5. Is it possible to just globally disable the code that strips out the JavaScript from pages or posts, altogether?

    • Hello Knott, that would mean removing some very important php code from the core files. So the answer is no, unfortunately. You can always try to insert the javascript code into the header or footer on your theme.

      Kind regards

  6. You’re a life saver, Manuel. Thanks for posting this.

  7. hello, thanks for your post, could you please tell me how to insert that code in a page of my wordpress site:

    function calculate_payment(theform) {
    var CV = parseFloat(theform.capital.value)
    var FV = 0
    var rate = parseFloat(theform.interest.value) / 100
    var nper = -parseInt(theform.period.value)
    var type = 0
    theform.payments.value = (CV * (rate / 12)) / (1 – Math.pow(1 + rate / 12, nper))
    }

    Kind regards !!!

    • Hello Laurent, thank you for your question. This is actually a function correct? If you are using a function in WordPress then you have to call that function somewhere else in a page or post.

      Let me know if you understand what I mean.

      Kind regards

  8. Most JavaScript should be placed in the header/footer, and this is a requirement for some scripts to function correctly. Adding JavaScript like this is not good, you should use the functionality already built into WordPress for example place this in the header:

    <code>

    </code>

    Or you can do a similar thing in the function.php file, the benefit of doing it this was is it’s cleaner, and it’s easier to add another page should it be used again in future like:

    <code>

    </code>

    Ricky

    • Hello Ricky thank you for your comment. Yes agree with you that the best method is to add the javascript to the header or footer but some are not technically minded and this method although not the best still works. Can you post your code again for others to view.

      Kind regards

  9. Hey, Yeah I do understand why you done it like this, but personally I think it’s easier the way it’s done below (with less chance of it going wrong and you getting lots of ‘support’ comments) though that could just be because I am technically minded ;-P

    <code>

    Put JavaScript Here

    </code>

    The above will only show whatever is between the PHP tags.

  10. This doesn’t explain how a single html page can use (reference) an external javascript file using such plugins. HTML addition as a snippet is clear enough, but how do you use a plugin for the equivalent of inserting references in the head section?

    • Hi Joan, thank you for your question. You are correct in regards to the post not explaining how to reference an external javascript to a single post or page. I have being wanting to edit this post some time back but things have being so busy :). In regards to adding a javascript reference in the header, the following URL wordpress.org has some great illustrations for this. Perhaps in the near future I will amend this post to better explain adding javascripts code.

      Once again thank you for your question and sharing your views.

  11. I am using the iFrame from the WP Edit (new name for Tiny MCE Editor) in a java script to post the result of a query.
    The iFrame shows plenty of space in the editor window, but once I pre-view the page, the iFrame is only about 5 lines high. The result of the query is cut off vertically.

    In the plug in, there is no other setting I can find to change the size of the display area. It is already set to 100% vertical and horizontal.

    Any thoughts?

    • Hi Joost, thank you for your question. I had a look at your website and my judgement tells me it could be related to your theme. Can you send me a private message through my contact form with the URL in question so that I have a look.

      Thank you

      • Here is an update to my question about sizing the iFrame.

        I discovered that I can influence the size by using px, instead of %.
        I now have it to cover as much width as possible, because the result of my query that is displayed in the iFrame is large (it is an interactive visualization).
        So although I am not sure if the % will work in some way, I am past my hurdle with that.

        I will submit a separate Q for a new issue with the iFrame.

        Joost

        • Hi Joost, it is good to hear that you have found a solution to your previous question. iFrames don’t work with percentage values, you have to use pixels.

          Regards

  12. WP edit seems to work well for most things. It fills out the basic WordPress post box nicely… I was having some issues posting embed code, but this helped :)

Leave a Reply to Webmaster Cancel reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

4 − one =