JavaScript in a WordPress post

How can I add

<a href="javascript:function foo(){alert('hi');}" title="alert">
    Drag to your bookmarks bar
</a>

to my WordPress post?

Read More

I built a bookmarklet and I want to pass it through my blog, but WordPress is stripping out the javascript from my post when I save it.

Related posts

Leave a Reply

5 comments

  1. I have no issues embedding that code in the HTML editor on my wordpress site. There is a problem with your javascript code- that defines a function, but never calls it. I have

    <a href="javascript:alert('hi');" title="alert">Drag to your bookmarks bar</a>
    

    in a post, and I get the alert when click, as well as the bookmarklet.

  2. The issue is likely to be caused at the browser end. Chrome’s XSS was the problem for me and I solved it by adding the line header ("X-XSS-Protection: 0"); to wp-blog-header.php in the root folder of my installation. This may not be ideal as it applies across the whole site. It would probably be better to add it where it would only apply to the post/page which needs to render the bookmarklet.

  3. This is old, but still relevant with Version 4.9.5 for wordpress, so I answer with my solution for this:

    WordPress filters out any Javascript you use in your Posts or pages, that is why your code gets lost. I did the following steps to add a “javascript:” Link:

    1. Add the Link you want to your post, use “#” as the href and add a id to the tag (in Text-Mode of the Editor):
    <a href="#" id="idOfYourLink">This is my JS Link</a>
    
    1. Install a Custom Javascript Plugin. I used Simple Custom CSS and JS
    2. Add the Javascript you want with help from the plugin:
    jQuery(document).ready(function( $ ){
      function yourFunction() {
          alert("It works");
      }
    
      jQuery('#idOfYourLink').on("click", yourFunction);
    });
    

    The important part is adding the on-Handler to the Link you want to use. Now the Javascript is loaded right after the page got loaded. And a click on the link will call the function yourFunction

  4. I guess that wordpress editor is used to work with textual data/content. So, to add your js you can find plugin for adding custom js. Also you can add a Custom field to the posts.
    enter image description here

    Let it be “custom_js” – the name of a field that would contain js code. And then edit theme post temlate, adding “echo” of custom_js.

    <?php
    //single.php
    echo get_post_meta( get_the_ID(), 'custom_js');
    ?>