How to insert JavaScript into WordPress pages or posts?

1. could Add JavaScript to WordPress using functions.php

his uses the IS_PAGE function which you can find here: https://developer.wordpress.org/themes/basics/conditional-tags/.
You can actually use various other options if you want to add the script only in specific conditions such as:

  • is_single(),
  • is_front_page(),
  • is_home,
  • is_admin etc.

for example :

  • is_single( ’17’ ) – uses the post ID
  • is_single( ‘My Post Title’ ) – uses the title of the post to check whether this is the post to add the file to
  • is_single( ‘my-post-title’ ) – checks against the slug of the post
  • is_single( array( 17, ‘my-post-title’, ‘My Post Title’ ) ) – this checks if any of the conditions post ID is “17”, slug is “my-post-title”, or title is “My Post Title”
  • is_single() – other variations of the is_single function using an array of values to check against
// WordPress custom function
function my_custom_function(){
    ?>
    <script>
        // Your function here
        jQuery(window).load(function(){
            console.log('Hello World!');
        });
    </script>
    <?php
}
add_action('wp_footer', 'my_custom_function');

2. could Add Javascript to WordPress using header.php

In certain cases, you might want that the JavaScript file is used in all your site, but you don’t want to use a plugin to do this. For example, if you want to add a 3rd party script in all your pages, (e.g. the instantpage.js script to make your website faster) you can insert the script, or add the referenced script file itself, in the head of your header.php template file.

THIS IS NOT IDEAL. If you update your theme, you might lose these changes. If you still would like to do this directly, it is highly recommended that you create a child theme.

<script type="text/javascript" src="https://cdn.collectiveray.com/scripts/myscript.js"></script>

To use your written code, do like below :

<h4 class="heading4">
<a href="<?php the_permalink() ?>" > Heading goes here </a>
</h4>
<div>
<script type="text/javascript">
<!--
myscript();
//--></script>
</div>

3. 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' );

warning : Enabling the script tag via this method disables the security feature sitewide for any user permission level.

4. Use a plugin to enable script includes

If you would like to simply use a plugin for embedding a javascript reference to the WordPress theme’s header or footer file, ‘Insert Headers and Footers’ plugin is an easy option.
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.

5.add directly with “custom HTML” block

	<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {packages:["orgchart"]});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Name');
        data.addColumn('string', 'Manager');
        data.addColumn('string', 'ToolTip');

        // For each orgchart box, provide the name, manager, and tooltip to show.
        data.addRows([
          [{'v':'Mike', 'f':'Mike<div style="color:red; font-style:italic">President</div>'},
           '', 'The President'],
          [{'v':'Jim', 'f':'Jim<div style="color:red; font-style:italic">Vice President</div>'},
           'Mike', 'VP'],
          ['Alice', 'Mike', ''],
          ['Bob', 'Jim', 'Bob Sponge'],
          ['Carol', 'Bob', '']
        ]);

        // Create the chart.
        var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
        // Draw the chart, setting the allowHtml option to true for the tooltips.
        chart.draw(data, {'allowHtml':true});
      }
   </script>
<div id="chart_div"></div>
Share this Post