I want to add small javascript program in wordpress post, please let me know how to add / execute in WP Post ?


Yes I tried, but no luck.

First I added HTML Code & JavaScript in Post Text Editor, No Luck, Then I created Separate JS file & posted only HTML code & called js file using <Script src=<Path of the JS File>> - No Luck.

4 Answers 4


One option would be to create a shortcode exclusively for that script. Even thought it's not an elegant solution, it works. In your functions file (functions.php) of your theme add:

function custom_script_shortcode(){
    $code = '<script>';
    $code .= 'var foo = "bar";'
    $code .= '</script>';
    return $code;
add_shortcode("custom_script_shortcode", "custom_script");

And in your post editor then add the shortcode:


Just be careful when you assign your JavaScript to the variable $code so you don't close the string with " or '


You can add your script on header or footer normally with . Or you can hooked your script on function.php like this way:

function theme_name_scripts() {
wp_enqueue_style( 'style-name', get_stylesheet_uri() );
wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );

If it is for all the posts, an external script is always a better idea, linked with wp_enqueue_script() (see this article for more information).

If you only want to add a code to a single post, simply write it in the editor (into a script tag, in the "Text" tab).

  • Hi, just want to add in a single post, i tried in the text editor HTML & JS, but its not executing.
    – Rajesh
    Jul 5, 2015 at 5:21
  • 1
    When you save your post (save the draft or publish the article), is the script tag still here? If it disappears, that means you don't have the rights to do that, you must be at least an editor.
    – Jeremy
    Jul 5, 2015 at 8:27

If you go in and edit the post, and click the "Text" tab, and enter your code in <script> tags:

<script type="text/javascript">

and update the post, the content should save as

<script type="text/javascript">// <![CDATA[
// ]]></script>

which should execute when the post is viewed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.