WordPressCategory

3 methods you can use to insert JavaScript into WordPress pages or posts

7 min read
Douglas Karr

Looking for ways to insert Javascript onto your WordPress pages or post? You've come to the right place!

What is Javascript?

JS, an acronym for JavaScript, is one of the most popular client-side programming languages. Developers use it to implement interactive features on websites.

Given that it is a client-side language, Javascript enables you to implement interactive and dynamic features onto your website even after your page finishes loading.

On the other hand, WordPress is coded in PHP, a server-side language. That means the server processes your website code before being displaying it to users.

Therefore, using Javascript opens up new options for your website.

Can you use Javascript on WordPress sites?

In short, yes you can! In fact, combining the powers of Javascript with Wordpress gives you the best of both worlds.

Once you get familiar with how you can implement custom Javascript on your WordPress site, you can look into enhancing the efficiency of your code and acheive the customization that you want.

In fact, many WordPress plugins and WordPress themes use JavaScript to power their functionality.

What can JavaScript do for WordPress sites?

Typically, the WordPress editor both autoformats your text and restricts the types of tags you can insert into your content. While some users who are attempting to insert custom 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:

  • Analytics - most analytics and tracking services would need you to add a Javascript code snippet onto your website. Some examples include Google Analytics, Facebook Pixels and so on.
  • 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. You can also add live chat widgets.
  • 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. This allows you to include email marketing opt-in forms or contact forms on your website.

For most users, the most common use case for adding JavaScript to WordPress is integrating third-party tools and services into your site. In this article, we will examine three methods you can to integrate your Javascript files with WordPress, with step-by-step tutorials on how you can do so.

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 Wordpress plugin to enable script includes

There are plenty of plugins out there for managing JavaScript within 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:

scripts-styles-1

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

scripts-styles-2

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.

Here is a list of other popular Wordpress plugins you can consider:

Here are some of the best WordPress free plugins for JavaScript management:

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 custom 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.

add-field-group-acf

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.

post-page-field-group

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-template

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

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

before the </body> tag.

footer-script-template

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.

In summary: limitless possibilties for your WordPress website with Javascript

Once you add JavaScript to WordPress, it opens up a lot of flexibility for your site. From analytics and tracking scripts to interactive features, you can now add them with ease onto your Wordpress website.

Depending on your level of proficiency, you can manually add JavaScript using a child theme or a custom plugin, or simply use one of the available WordPress JavaScript plugins.

Start creating new possibilties for your website today.

Editor's note: GoDaddy's WordPress Hosting offers you access to thousands of free themes and plugins. Your WordPress site is fully managed with built-in security (malware scanning and removal), daily backups and automatically updated WordPress software, plugins, extensions, and PHP versions to optimize performance and reliability — and fast load times. Get started today!

This article was originally published on September, 14, 2020 and updated on May 23, 2023.

Products Used