Adding JavaScript to Your WordPress Site

Are you using WordPress, but need to add custom JavaScript to your site? Then this guide is for you.

NOTE: If you are using non-WordPress sites, then our platform specific guides will be a good resource for you to review.

To add special JavaScript to your site, like you would do if you are trying to implement something from our JavaScript Events API, then you need to have a way to insert JavaScript into your page(s).

You have 2 options for inserting JavaScript and/or jQuery.

OPTION 1: Use a WordPress Plugin

You could use a WordPress plugin if you want to insert JavaScript into your site. There are a variety of plugins out there. One of the more popular plugins is Header and Footer, but there are other plugins too.

CRITICAL NOTE: OptinMonster does not officially endorse any plugin that you use and OptinMonster is not responsible for and will not provide any support for any plugins you use to insert JavaScript. If the plugin you decide to use messes up your site in any way, that is something that you will need to address between you and that plugin’s author. For example, if you are concerned about the Header and Footer plugin mentioned above and using it alongside Yoast SEO, this is something handled between those 2 entities, like they have here.

Essentially, you will need to copy the JavaScript embed code from OptinMonster, then follow the instructions of whatever plugin you choose to use.

OPTION 2: Add the JavaScript code to your Theme’s footer.php file

While everyone’s WordPress setup is different, your theme should have a footer.php file. To access this you will need to go to do the following:
WordPress Dashboard > Menu Item: Appearance > Sub-Menu Item: Editor.

When you get to your editor screen, look for your Theme’s Footer (footer.php). Click that.

Now your Theme’s Footer (footer.php) should be showing up. Go to the code area below <?php wp_footer(); ?>. Below that, but above the closing </body> tag is where your code should go.

Therefore, it should looking something like this:

<?php wp_footer(); ?>

// Your JavaScript or jQuery goes below
<script type="text/javascript">

// This code below allows us to use jQuery, which is already loaded in because of OptinMonster.
jQuery(document).ready( function($){

    // In this example, we will have JavaScript occur during the OptinMonster event called 'OptinMonsterOnShow'. Your code doesn't have to load during this event however.
  $(document).on('OptinMonsterOnShow', function( event, data, object){

        // Your additional jQuery code will go here.

  }
}
</script>
</body>

After you have added your code, double checked for proper syntax, then click Update File. You’re JavaScript is now loaded on all of your pages on your site.

Now that you know how to add JavaScript to your site, check out what you can do with OptinMonster’s JavaScript Events API.