spark plugs

3 ways to insert JavaScript into WordPress pages or posts

WebsitesCategory
7 min read
Douglas Karr

Editor's note: This JavaScript post was originally published on September 14, 2015 and updated on September 16, 2018.

The WordPress editor both autoformats your text and restricts the types of tags that are inserted into your content. While some users who are attempting to insert scripts find this frustrating, it’s not a design flaw. Blocking the ability to insert scripts is a security feature.

The purpose of a content management system (CMS) like WordPress is to separate content from design. Ensuring that the administrator sets formatting and layout options at the theme level prevents the WordPress site’s authors from modifying the design.

JavaScript can completely transform those restrictions.

With JavaScript, you can apply styling, layout and content changes outside the boundaries of the page or post you are authoring. In fact, there would be no restrictions from uploading malicious scripts by your authors.

While this is a good restriction for the average author, there are valid reasons to add JavaScript to specific pages or posts:

  • Players — Some audio and video players require a script to display the player within the page.
  • Interactive pages — Interactive pages and calculators require embedding of third-party scripts within a site.
  • Third-party forms — Subscription and lead generation forms often have remotely loaded scripts that need to be included in the header, body or footer of the page.

How do you add JavaScript to WordPress pages and posts?

We'll take a look at three options for adding JavaScript to WordPress:

  1. Disable WordPress filtering of script tags
  2. Using a plugin to enable script loading
  3. Using Advanced Custom Fields

Let's get into the details.

Method 1: Disable WordPress filtering of script tags

If you trust that your authors won't get themselves into trouble, you can disable the blocking of script tags from within JavaScript. In wp-config.php within your root web directory, you'll need to enable custom tags by adding the following line of code:

define( 'CUSTOM_TAGS', true );

Within your functions.php page, you can add the following code:

function add_scriptfilter( $string ) {
global $allowedtags;
$allowedtags['script'] = array( 'src' => array () );
return $string;
}
add_filter( 'pre_kses', 'add_scriptfilter' );

Note: Once again, we have to warn against using the above method. Enabling the script tag via this method disables the security feature sitewide for any user permission level.

Method 2: Use a plugin to enable script includes

There are plenty of WordPress JavaScript plugins out there for managing your pages or posts. At times, you will need to load your JavaScript within the <head> tags of the page or after your content adjacent to your </body> tag.

Sometimes you may wish to load JavaScript sitewide; other times specific to a single page or post. After testing many of the plugins, the most comprehensive plugin we found was Scripts n Styles.

The plugin allows you to include scripts at a global level, sitewide:

Global Settings for the Scripts and Styles JavaScript Plugin for WordPress

Or you may insert scripts at the page or post level:

Scripts and Styles Plugin Field for Script Inserts

The plugin allows you to include both an external script source or to copy and paste your own JavaScript within the <head> tags or above the </body> tag.

If you're using this plugin, you may wish to modify user permissions and incorporate contributors much more than authors. Authors would be able to publish the post and put the JavaScript live; contributors would only be able to save the posts without publishing them.

Method 3: Use Advanced Custom Fields

Advanced Custom Fields is a widely used plugin that allows you to implement custom fields without having to develop a ton of code.

With more than 1 million installations, Advanced Custom Fields is a proven, well-developed, and well-supported plugin.

Install and activate the plugin and you will have a new menu option in your Administrative menu called "Custom Fields." Our goal with this example is to add a field that's available only to administrators that will embed either a JavaScript source file or JavaScript code within the head or before the closing body tag.

1. Navigate to Custom Fields > Custom Fields and click Add New.

2. Name your Field Group. We named ours JavaScript Settings.

Advanced Custom Fields Plugin Usage for Adding JavaScript to WordPress

3. We enabled a rule to display the option only if the logged in user type was Administrator, ensuring that the fields could only be applied by an administrator of the site.

4. We'd like to display the fields in a section beneath the content area on the text editor, so we're going to select Standard on the style of the Field Group.

JavaScript Settings in Post Entry

5. Now we need to add our Header Script and Footer Script custom fields and output them correctly. There are two key settings; the field name that will be referenced later in the template code and the formatting. You must set the formatting to the "Convert HTML into tags" option so that the contents that are pasted are properly executed in the template.

At this point, the fields will properly display within the Administration panel when an administrator is logged in. Any data entered will be saved and associated with the page or post once it's saved or published. However, they will not display within the template until you edit your template files.

6. Within header.php in the active template, we will add:

<?php the_field(‘header_script'); ?>

before the </head> tag.

Header Script Code With WordPress Template

Within footer.php in the active template, we will add:

<?php the_field(‘footer_script'); ?>

before the </body> tag.

WordPress Template Source Code for Footer Script

7. Save the template files, update the page or post that you've specified JavaScript in, and click publish. The page or post will now be published with the JavaScript properly inserted into the template.

The Advanced Custom Fields option offers quite a bit of functionality. You may want to define your rules specific to certain users, published pages, or page templates rather than Administrators and all posts and pages. We’d highly recommend narrowing down access to adding scripts to only the pages, posts and users that they are required for.

A caution about JavaScript and SEO

While JavaScript usage can be beneficial to developers, it can also be problematic for SEO. Search engines will do their best to crawl, execute, and interpret your JavaScript code, but this process is far from guaranteed.

A WordPress page or post will only appear in search engines results (and rank well for SEO) if the search engines are able to crawl, render, and digest your full content. When JavaScript is implemented poorly, this will not happen. If the search engines are unable to fully crawl and render your content, the crawlers will depart and your content will simply not rank in search.

To prevent JavaScript issues with SEO, make sure your content is crawlable, obtainable, and isn’t developing site latency obstructions. It is also wise to use real URLs and set your Robots.txt file to allow crawling of JavaScript.

If you are unsure about the health of your JavaScript code, just use the Fetch as Google option. The Fetch as Google tool lets you test how Google crawls or renders a WordPress page or post. You can use this tool to see if the Googlebot can access a page on your site, view how it renders the page, and determine if any page resources are being blocked to the Googlebot. This tool simulates Google's crawl and render process, so it is the perfect tool for debugging and discovering possible JavaScript issues within your website.


Love wasted time? (Neither do we.)

Fumbling for login credentials, running endless updates, explaining product purchases... No thanks. We built The Hub from GoDaddy Pro to save you an average three hours per month for every client site you maintain.

Sign up for Free

Products Used