Once you enter the world of PHP, it’s really hard to go back to Javascripts, but they still serve their purpose. If you can replace a Javascript with PHP code, tags, or script in WordPress, do so. Your life will be much easier. If not, here are a few tips to make your Javascript work in WordPress.
You can only use Javascript in full different versions of WordPress. WordPressMU driven sites like wordpress.com have set the tag filter to strip out all use of javascripts in posts, along with all CSS styles and many HTML tags for “security reasons”. You can therefore only use Javascript in the full version of WordPress, from within the posts and template files.
Using Javascript in WordPress Template Files
A lot of people want to put clocks, forms, calculations, and other widgets and gadgets driven by Javascript on their WordPress full version site. While I recommend you try to find a PHP script or Plugin replacement for the Javascript, you can still use Javascripts in WordPress templates.
If you have a lot of javascripts that you will be using consistently in your WordPress template files, then first try to put all the scripts into one group Javascript file rather than a bunch of small files. Even if you don’t use the scripts for every single page or post on your site, they can still just sit there in the single Javascript file until called.
Make sure that each script is defined by its function name such as:
function updatepage(){var m="Page updated "+document.lastMo.......}
Let’s assume that you called your group javascripts file scriptfile.js and it contains the updatepage script. When you want to use the example updatepage Javascript in a WordPress template file, add a link to the Javascript file in the header.php between the meta tags and the style sheet link in the head section. Here is an exmaple of what to add for your Javascript file link, changing the name to your script file name:
<script type="text/javascript src="/scripts/updatepage.js"></script>
Be sure that you define the type correctly, as your site will not validate without it.
In the place on your index.php, single.php, sidebar.php, or whichever template file you want to activate the Javascript, place the following code in exactly this format, changing the name to the function call of the script:
<script type="text/javascript">
<!–
updatepage();
//–></script>
Be sure and thoroughly test the generated pages with the script to make sure it works.
To Include Javascript Inside a WordPress Post
WordPressMU and wordpress.com users could include Javascripts inside of posts, but the developers have decided that this poses a security risk and so all javascript and many CSS and HTML tags will be automatically stripped from your post contnet. But you can use this technque within the post of the full version of WordPress.
To include a Javascript inside a post, you need to combine both the call to the script file with the call to the Javascript itself.
<script type="text/javascript" src="/scripts/updatepage.js"> </script>
<script type="text/javascript">
<!–
updatepage();
//–></script>
If your Javascript doesn’t work, triple check that you haven’t made any errors during the cut and paste into a group or single file. Be sure you used a text editor and not a word processing program to create the Javascript file. Check the name of the function in the script file as well as on your site. Not all javascripts may work, and could possibly conflict with your PHP commands, but this is very rare.
If you are using the full version of WordPress and having trouble with including a lot of javascripts inside a post, try using the Text Control Plugin. This allows you to control WordPress’ automatic formatting features on a global or per post basis the ability, turning them on and off. The WordPress automatic formatting features can quickly turn a code into something readable instead of executable. To use this plugin, the entire post must be setup in HTML tags using paragraph tags and such as they will be turned off by the lack of formatting, and set the plugin options on the post that you will be using the Javascript on to have No Formating and No Character Formating. As a reminder, when using the Text Control Plugin, you must first Save and Continue Editing the post in order to see the Text Control Plugin options. This is only to be used by the brave as it is a lot of extra work.
DO NOT PASTE JAVASCRIPT CODE INTO THE COMMENTS!
They will be stripped automatically by WordPress.com. The issue to solving your problems with using Javascript inside of a post of Page in WordPress is not the Javascript code itself. Showing it to me won’t help anyone. The problem is with WordPress. You MUST follow the instructions above to the exact letter. Then it will work. Javascripts will not work in WordPress.com blogs, no matter what you do.
Site Search Tags: javascript, wordpress, scripts, files, templates, help, java, tips
Copyright Lorelle VanFossen
© Reprinted with Permission










52 Comments
Lorelle, I have tried to include some javascript in a post on wordpress.com but when I save it the script tags are removed. Do you have any idea why this happens? Thanks.
Because of this change in the code, which I am furious about.
I do not think that Javascript will be allowed in wordpress.com hosted sites as that is a security risk. I tried one early on in the development as a test and it worked per the article.
It does work for the full version of WordPress.
That’s a pity!
It sucks big time that the ’style’ and ‘onXXX’ attributes are not allowed either… Bugger.
No joke. Please complain loudly here on Ryan’s site so we can at least get inline styles back.
Big bugger!
Hi Lorelle
i have read a lot of your posts and almost ALL of them seems like to be copied. Copy/Paste woo. this one is identical with http://codex.wordpress.org/Using_Javascript
i hoped to find a solution on the second or third Search Engine Result Page and they ARE ALL THE SAME …
i am sure this comment won’t last long and I am NOT concerned about it, but I really felt frustrated finding the same post on your site and the wordpress pages too.
Adrian
They are not copied. I wrote all of the articles about using Javascript in the Codex, on my main site, and on this site. Oh, and if you missed it, I’ve written the same information throughout the WordPress Forum.
You will find different information in each of the articles, but I wrote them all, so you will find duplicate information because there is only so much that can be said about using Javascript in WordPress.
Isn’t it nice that you can find the “right” solution in so many places, too.
So, if the information you are looking for is not within those documents, then what is it you want to know? That’s the bigger question to ask.
well Lorelle, unfortunatelly it isn’t the right solution for me . wordpress it still strips tha javascript tags. I AM SURE THERE HAS TO BE A SOLUTION THAT REALLY WORK. anyway, i didn’t wanted to upset you in any way and i beg you pardon for my words. Anyway
i invite you to read your article here and the one on codex hihih .. (there is no difference). SO, once again, please forgive me if i said something wrong and if i make it work for me, be sure i will publish my solution here , as a comment. Deal?
Nice to meet you.
Adrian
Actually, Adrian, you just saved me.
Just before a major server move for wordpress.com, the developers decided to add to the stripping filter for post content (mentioned in the comments above and more info is here) . This move stripped out all kinds of CSS and HTML as well as javascripts. I put a note of the change in the article, but then the server move came the next day or so and many of my posts were lost in the shuffle and were restored from backups - thus the correction that I thought was in there still was removed.
Lucky for me, you came along and spotted it, even though mention of the loss of use of scripts and CSS and HTML was mentioned in the comments.
I’ve now edited the article back to correct the screwup, so thanks for the help.
So the answer to the issue of javascript in wordpress.com blogs is NO. There is no solution and nothing you can do about it but complain loudly to the developers through the FEEDBACK button.
Squeaky wheel and all that.
Oh, and if you will notice at the bottom of the post, it says “Reprinted with permission”. Since I wrote all the documents involved, I gave myself permission to reprint them here. Ain’t copyright a nice thing.
excelent job with the copyright permission. no comments
. and i saw your words about yelling on Ryan’s site. And if i was saving you in some way , I am glad i could do some good stuff here. Anyway, i think i will search for help to another site, that really tell me what to do, not just fooling around ..sorry if i am too cruel. i didn’t intend to. i am just digging for a little solution, so i can run third party javascripts on my site. Thanks you for your help so far. I don’t have time to chat. bye. Adrian
You can try your darndest, but you will NOT be able to run javascript on wordpress.com. A full site, sure, but there is no way.
This is not just for you but for everyone. If you want javascripts, then get the full version of WordPress. The free version is for blogging, not running ads or bells and whistles. Get your own hosted site and the free full version of WordPress for that.
Hi
I did like your blog postings and comments but i have soem problem if some1 could help me out.
Does anyone know how to pass html table data from parent to a child form html table ? Or may be you could let me know any URL related to this topic.
Any kind of help is highly appericiated.
Thanks
Imran Hashmi
http://www.visionstudio.co.uk
You will need to check with a PHP and MySQL expert. All you basically need to do is use PHP template files or PHP “get” commands inside of a table to put the information in the table.
If you can be more specific, someone or I might be able to help you, but I recommend that if you are using WordPress, you leave a message in the WordPress Support Forum to get your question answered.
Hello … I have a simple javascript that I would like to run in a new PAGE in WordPress. I have my own hosted site with WordPress 2.
Do you know of a site URL that shows an example of JavaScript being used on a PAGE (not a post)?
To accomplish this on my wordpress installation, do I follow your suggestions above on “Using Javascript in WordPress Template Files”? Kindly verify if so. if not — kindly suggest what I can do to add javascript to my WordPress installation.
I’d just like to come up with a new page that will show my current photoblogs from SplashBlog.com.
To help clarify this for others, you mean Page as in a Page outside of the WordPress Loop posts, right?
You can include javascript as I’ve written in a Page. It will work the same. Just make sure you include the call out for the Javascript inside of the Page post area or use a Page template file with the javascript called out in the header so it will load when the Page is generated.
I have several Javascripts running within this page on my main site from within the template files and within the Page post content area. View the source code to see them in action.
Now, if you want to run Javascripts on any post or Page on WordPress.com, you are out of luck. That is not available from the developers at this time.
I’d like to ask you a javascript question. I have included the code above (for template files) in my header to call a “protection” script that disables right clicking. I know people hate this, but I frequently use country graphics, and these artists insist upon no right click, etc. The script works, but I just can’t get it to validate. I am missing something that must be right under my nose. Any advice would be appreciated.
First, your site is set to DOCTYPE Strict XHTML. Change it to
DTD XHTML 1.0 Transitionaland see if the page validates or not. Strict is serious stuff.Second, remove
language="javascript"from your script call out. That’s old school.Third, if these don’t solve your problem, find another right click script. We use Disable right click script II (on images) - By Dynamicdrive.com on our main site. Be warned though, in Firefox, the warning comes up when you right click on images only (that’s CRITICAL - do not turn off right click on everything) and once the user clicks “OKAY”, the Right Click menu comes up and the user can then do whatever they want.
We think of disabling right click on images only as a mild deterrent. It reminds people that stealing images isn’t nice or right - in fact, it’s illegal. But it doesn’t stop Google Images from grabbing all your images and allowing people to hotlink to your image, using your bandwidth. It is more like a “warning”.
But the others are right. Turning off Right Click completely is very bad manners.
Let me know how this works out.
Thanks for all the tips, Lorelle. Since you encourage people to replace Javascript with PHP code where possible, I wonder if you can point to any good tutorials on how to do this?
I’m mainly interested in integrating a del.icio.us tagroll to a static page, so it shouldn’t be too complex a trick, I hope.
You’re welcome but I don’t know what a del.icio.us tagroll is. As for adding one to a static page, I assume you mean a Page rather than a post page, as in adding this to WordPress? Or are you talking about an name.html file that is not part of the WordPress Pages or posts?
The best I could do right now, since I’m on the road and not a PHP coding expert in any way, would be to search the net to find a solution, probably a plugin, to make this work for you. If you want to add this to a specific page and not make it part of a template file, then you will probably need to run the WP-Exec or RunPHP WordPress Plugins to allow the code to be interpreted on a WordPress generated page. Otherwise it is turned into text or borks the page.
I need more information before I can offer more.
A tagroll is a single line of Javascript generated by del.icio.us to publish a customisable tag cloud for your del.icio.us bookmarks (link may require login).
I do mean a Page I’ve generated on WordPress, yes (a links page).
No reason why you should search on my behalf - maybe the plugins you mention will solve my problem. Thanks.
Ah, then the plugins I mentioned may help, but converting such a a script to PHP will be rather challenging as you will be calling in information from an external offsite source rather than from a database or onsite source. That will be the trick. PHP might not have that capability.
Javascript is not “bad”, it’s just that a lot of scripts can be replaced by PHP, but not all. In this case, you might be up against a wall.
The javascript will work with the Text Control WordPress Plugin which does work in WordPress v2+.
Let me know what you find out.
hi lorelle and all folks
thankyou for this javascript discussion.
i am attempting to put this javascript below on my post and pages.
this javascript worked beautifully on my wordpress 1.5
now i have wordpress 2.0.2 with the option of upgrading to 2.0.3
QUESTION 1
what is a “full wordpress” ? and how do i know if mine is “full”? i have installed wordpress via my cpanel/fantastico host.
QUESTION 2
i cannot discover, even after reading the posts over and over, whether i can or i can not put javascript on posts and pages.
QUESTION 3
when i make a post or page, there are 3 choices:
template, archives, links. which should i use for posts and pages?
alto
1. If you installed it yourself with any method, it is the full version of WordPress. If you have full access to manipulate your WordPress Theme in any way, it is the full version of WordPress.
2. You can, and cannot, put javascript in posts and pages. It is fully outlined exactly how to do both in the article above.
3. Posts are handled by template files which apply to the post type displayed. The index.php is usually the default for everything, if you have no other post displaying template files. The single.php is the only template file that displays a post, if present, otherwise it defaults to the index.php. The archives.php is for displaying archive categories (by month categories) if you have it, otherwise it defaults to index.php. The page.php, if you have it, generates Pages, otherwise it defaults to index.php. For more on which template is which and how they work, see Stepping Into Templates.
If you are using the javascript consistently on every post or page, then put it in the appropriate template file. To use it in a post, follow the instructions above. I’ve removed your javascript code from the comment as it doesn’t help. You are linking to an MP3 file, why don’t you just link to it? Why do you need javascript? Anyway, follow the instructions to the letter, with every format copied and it will work for you.
Since these are the only methods to add Javascript to WordPress without stress or strain, while frustrating, it works. Let us know if it does and good luck!
thankyou lorelle
i have learnt a lot through this topic.
you make things make sense.
any chance of cloning yourself
and spreading yourself around the world?
to make my script work, i installed a fresh wordpress 2.0.3 and it works. it would have worked on the 2.0.2 also - it seems that i had some messy code which was preventing the script from working.
thankyou again.
alto
Glad to help and I’m glad it “fixed itself” so to speak. Using code, tags, and javascript within a WordPress post or Page is a pain, without a doubt. I used to use a lot of it and now I’ve streamlined it only to the barest necessities, finding other ways around it cuz it such a pain.
Thanks for letting me know. As for the cloning…when the US finally elects a progressive thinker instead of someone from the dark ages, this might just happen.
Hi Lorelle,
Great post! I am redesigning the intranet site at work, and one of the requirements is to have a folder library in a WordPress page. I found a javascript template for it and I used the code you supplied for the post but I get no results. The url linking to the js file is accurate, but am I supposed to change the to meet any particular attribute? I have no knowledge of js, and I do apologize if this is a ‘no-brainer’ but your help would be much appreciated.
The previous post auto-formatted and deleted the snippet of code I was making reference too: ’script type = “text/javascript’
Yes, WordPress.com does that. Sorry.
The trick to this is as stated: Go through the directions very carefully and follow every instruction.
Putting javascript inside a post or Page in WordPress is very tricky. Sometimes it’s better to create a static PHP page and manually add links within your sidebar and other template file areas to it when using Javascript than to put it inside of a post or Page.
For instance, there must be a line break (just an ENTER) between each line in the script call out code. It cannot be on one line. The link to the javascript must be in the
headsection of theheader.phptemplate file.This works, but every detail as described in the article must be followed. I do this all the time on my full version WordPress sites, but even I’ve slowed down and found other ways to do this because it is so fussy.
I don’t know what you are calling a “folder library” but if it is just a list of folders within a directory, then type them in as links manually, unless there are tons. Good luck and let me know how it works for you.
We have a huge repository of files that the manager wants all users to have access to. I found the perfect script for this folder tree here I want to embed this tree in a wordpress page.
I will try the static page route and let you know how it goes!
Joseph, I can’t help you with the specific javascript, so stop trying to post it.
Follow the instructions as described in the article EXACTLY and it should work. I can only help you with the WordPress side of things, and this process works. It works with more than 100 javascripts I’ve used on my main site. There are no missing steps that I’ve found in the two years of using this method. Good luck! And again, let me know what you find out.
Hi Lorelle,
Cool site with cool stuff…
I am PHP Programmer. I have a requirement from my client that needs to be fixed.
He have a wordpress-mu (1.2.1) intalles and there are several blog sites are running under it. This is his feedback,
” We’ve had issues posting HTML into wordpress. WordPress wants to format the html after we post an article. Even if we only use the “Code” tab, the wordpress system will try to format what was pasted in. Here are some examples of the formatting:
formats out javascript tags
adds after each carriage return
changes — to –
Please look into creating a plugin that will bypass *all* the formatting when we post an article through the Code tab.”
Please suggest on this.
ThanksNaveen
A lot of people mistake the CODE HTML tag as something that will convert code into something readable in a blog post. It doesn’t. It only changes the
fontlike bold and italic.In a WordPress post, code is code. At the very least, the code will be converted and broken up so it isn’t code as a protection, which is the standards for WordPressMU blogs.
However, there are several ways to converting code into publishing code.
I recommend reading:
WordPress Plugins That Help You Write Code
WordPress.com Blog Bling: Signatures and Writing Code
Writing Code in Your WordPress Posts
The first one offers some examples of the Plugin options. However, they may still require conversion so the < looks like < and all quotes and apostrophes are changed to HTML character entities so the code can be copied and pasted without causing problems.
I want HTML (includes javascript) contents into post. But wordpress formats and changes few tags and strips the javascript tag(though i have disabled the option of using Rich Text Editor). I want to override wordpress formatting on per post basis.
With this scenario, bellow are my question:
1)Is this wpautop function is a global or specific that takes care of formatting ?
2)How can i avoid wordpress formatting only for blog post?
3)Is there any functions that takes care of blog post section only?
4)What does the function wptexturize does?
Thoughts are welcome
As described in the article, Text Control Plugin is your best answer, though I’m not sure if it continues to work in the most recent versions of WordPress. You’ll have to check with the Plugin author. Then follow the instructions in the article for including HTML and Javascript in your blog posts. The answers to your questions are already given. Choose NO FORMAT and the HTML and Javascript will work. The rest will strip out code.
Can I add javascript widgets to a wordpress subdomain?
@emersondirect:
Do you mean a WordPress.com subdomain, like lorelle.wordpress.com? No. No Javascripts.
Ok, thats what I thought, thanks Lorelle. Is there a valid reason why?
Lorelle,
i want to compliment you on being the most responsive blogger i’ve ever seen!
i created a ‘hello world’ javascript .js file, which pops up a ‘hello world’ alert. then i put the code into my page, exactly as you describe above (i originally got the steps from the codex).
it worked. then later, without any changes to the .js file, or the page, it stopped working. i cleared my browser cache and disabled the WordPress cache, but still no dice. Any ideas? Here’s the page:
http://picnictoimpeach.us/home/hello-javascript
i noticed that the wp-email link on the page (email to a friend) malfunctions on the page with my hello world call. when i click the wp-email link, it fails to load the email form, and firebug reports an error from wp-email, somehow related to my script.
i placed the wp-email script in page.php, re wp-email instructions. the other javascript plugins on the hello javascript page work normally, including Riffly multimedia comments, ShareThis, and AddThis. wp-email works without error on all other pages of my site.
btw, re the utility of javascript: javascript is client-side, php is server-side. there are things you can do with one that you cannot do with the other (or not very easily). for example, you cannot do ajax with php, as ajax is client-side behavior (i think). Each language has unique benefits, right?
best,
j
another firebug report. i’m not really sure how to use firebug yet.
i completely removed super-cache (my site’s faster without it), disabled wp-email, and removed the wp-email snippet from page.php.
still not working.
@johny why:
The languages can cross wires. The error could be anywhere, associated with any thing and I’m not the one nor place to ask right now. I’m traveling. It could be something as simple as a quote mark or apostrophe out of place. Please try the more appropriate WordPress Support Forum for help on this, and please take care to not post code that reveals directories in your blog setup for security reasons. Good luck.
thanks, i will.
strangely, my script works outside of WP (np). if feasible, i hope someone might write a plugin, WP upgrade, or plug-in rules, to insulate in-page javascript from corruption by other plugins.
happy trails.
found the problem. after correcting my obvious mistakes, the script would still not execute until i removed the comments. is this a bug? a new standard? should the codex or WP be changed? also, WP did not preserve my line-spacing. Otto42 says line-spacing is critical in js. see the support log here.
@johny why:
You have the best help with Otto42. He’s one of my heroes!
Hi,
I want to use JS to hide the affiliate link in my WordPress blog but it doesn’t work, WP strips everything and ignores the JS.
eg. text
The rel=”external” is like target=”_blank” but is strict XHTML valid.
So I thought, the rel=external works because it’s referring to a JS file in the but the onmouseout=”window.status=” onmouseover=”window.status=” doesn’t work. Is there a way to add the functionality of onmouseout=”window.status=” onmouseover=”window.status=” to an external JS file in the of the page?
(I’ve found various plugins to hide affiliate links but they seem too complicated and too much work for an apparently simple job).
@ ben:
The explanation on how to include Javascript works. The issue of onmouseover is one that is deprecated as it is considered not web standard for accessibility, so you shouldn’t be using it anyway. But the correct methods for adding Javascript in WordPress are in the article. Just follow them closely and exactly.
Would really appreciate if you could tell me how I can get the following code to work on wordpress.com (this is for a text box in my sidebar via WIDGETS):
replaced “S” with “$”
Thanks in advance
@ gsik:
The code was stripped out and WordPress.com does not allow programming code in the Widgets or elsewhere. For other answers, see the WordPress.com Forums.
thanks for answering that for me.
I’m in the process of switching my website to WordPress and a magazine-style template. I’ve hand-coded my own HTML for over ten years, but Javascript and PHP are pretty much foreign languages to me. I’m not strong in CSS, either.
That said, I have many individual sound files and each one accompanies one article, so the sidebar wasn’t an option. Each sound file requires Javascript to run. Every one of them has its own individual code.
After reading your great article and realizing that I don’t have a clue, I tried throwing the Javascript reference (that is, the code that goes on the actual webpage, not the file it calls) into a table in the article. (Just a basic, one-cell table that I hand-coded into my individual WordPress page.) Bingo, it seems to work fine. I’ve checked it in Firefox and in IE.
I have no idea why it works, but in case this helps someone else… there it is.
I host my own WordPress site, and I’m using WordPress 2.3.3, in case that makes a difference.
@ Fiona:
Into a table? You do understand that tables are for data not design, and doing so can cost you? If I understand what you are saying. It is best to call the Javascript from an external file, but either way, this isn’t a WordPress issue.
I do recommend that you change from Javascripts to embedding the files as they load faster and are less…nasty to work with. Using the PodPress Plugin, you can embedded dozens of different types of audio and visual files easily, no mess or fuss. No Javascript.
Thanks, i have been having some probles with this, infact i was just about to give up on wordpress and javascript in posts.
Thanks for javascript tutorial
5 Trackbacks/Pingbacks
[...] Code Coffee’s Top 9 Javascripts for Your Website is worth a look if you are using the full version of WordPress. However, be sure and take a look at how to use Javascript in WordPress before you incorporate these javascripts into your WordPress blog or site. [...]
[...] Using Javascript in WordPress [...]
[...] Using Javascript in WordPress Digg it [...]
[...] not easy to put this Google Gadget inside a blog post. Users of WordPress (not WordPress.com), see this page for details, and I quote “…sites like wordpress.com have set the tag filter to strip out all use of [...]
[...] ולכן לא הייתי נמנע מלא מלהתקין אותם בכלל. דוגמה לתוספי: גאווה, אייגקס, פלאש| אייגקס וגאווה|אתר מבוסס אייגקס. חלק [...]
Post a Comment