Categories
JAVASCRIPT TUTORIALS WORDPRESS

How To Enable Javascript Code In WordPress Page

WordPress CMS by default blocks any Javascript code from running as part of the website’s Page or Post. This is done to to prevent any malware attacks or website hijacking through vulnerabilities created by enabling Javascript on the WordPress Page and Post level.

However, it is still possible to enable running of Javascript if the WordPress website owner knows what he is doing. The website owner can enable Javascript on WordPress using two methods:

Method 1: Installing a third party WordPress Plugin

By installing an external WordPress Plugin that allows adding Javascript per post, any non technical WordPress site owner can also enable Javascript on the WordPress Posts and Pages level.

Method 2: By editing function.php file of the active WordPress Theme

In this method, you would need to ftp to your installed and currently active WordPress theme directory and look for the file called functions.php. You will then need to hook a new PHP function that gets loaded right after the WordPress Post’s <head> section gets loaded. Below is an example of how to write such a hook function in your functions.php file.

function wp_hook_js() {
 ?>
    <script type="text/javascript">
        //Add your Javascript code here
    <script>
 <?php
}

add_action('wp_head', 'wp_hook_js');

In the above code you can see our new function wp_hook_js() that contains our Javascript code. However, in order for this function to get called, we use the add_action() function. From the above code, you can see that we are hooking up our wp_hook_js() function to ‘wp_head’. This is a hook that gets called whenever a WordPress Post or Page gets loaded.

Thus by using either of these two methods i.e. by using a WordPress Plugin or by editing our theme’s function.php file and adding a hook function, we can ensure our Javascript code gets executed each time a WordPress Post or Page gets loaded.

In addition to this, you can add custom CSS to your post using “Additional CSS” option under Theme Customization option you get when you go to the “Appearance” option in the WordPress Admin dashboard.

This is all that is required to be done in order to get custom Javascript codes running at the WordPress Page or WordPress Post level. Hope this article was helpful in giving an insight on how to get it all working.

Until next time, happy coding 🙂 !!