In some situations, you may need to add custom Javascript to your site. Normally, this would involve modifying your theme files. Let us see various options available to add java script to wordpress post/pages.

Option 1.

“Header and Footer Scripts” is a plugin to add custom JavaScript  to WordPress without modifying your theme.

First, let’s install the plugin:

1.Log in to  your WordPress site.Go to Plugins > Add new > Search for “Header and Footer Scripts”.

2.Click “Install Now” and activate the plugin.Once it is installed you can upload custom java script file using below steps.

3.Save your custom JavaScript code into a file with the .js format , Upload it into your site to this folder: wp-content/themes/your-theme/js/

4.Go to Settings > Header and Footer Scripts.

5. Now you will have two options to load the file either in header OR in footer, please refer below screen shot.

 

Use the location that match better your needs using this syntax as example:

<script src=”http://www.yoursite.any/wp-content/themes/your-theme/js/file.js”></script>

Option 2. Load custom JavaScript without a file

You can add your code directly into WordPress without the need for a custom .js file, for that use <script> tag as shown in below image.

Click “Save settings” button when you’re done.

Option 3. Disable WordPress filtering of script tags

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 );

Then, 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: we have to warn against using the above method. Enabling the script tag via this method disables the security feature site wide for any user permission level.

Leave a Reply

Your email address will not be published. Required fields are marked *