Using Javascript in WordPress Posts

Overview

  • In this sample we use Child Theme twentyfifteen-child based on twentyfifteen Parent Theme
  • Create Javascript function start_slider() in slider.js under WordPress Parent Theme Directorywordpress/wp-content/themes/twentyfifteen/scripts
  • Note get_template_directory_uri() function returns : http://localhost/wordpress/wp-content/themes/twentyfifteen
  • Enqueue the JS script  slider.js  via wp_enqueue_script in functions.php of your child theme [  wordpress/wp-content/themes/twentyfifteen-child ]

Implementation

functions.php:
---------------------- 
function my_js_scripts() 
  {
  wp_enqueue_script( 'SLIDER',  get_template_directory_uri().'/scripts/slider.js', array( 'jquery' ),'0.9', false );
  }
add_action( 'wp_enqueue_scripts', 'my_js_scripts' );
-------------------------

The resulting HTML will now load JS file slider.js.
The output of the resulting HTML code looks like: 
<script type='text/javascript' src='http://localhost/wordpress/wp-content/themes/twentyfifteen/scripts/slider.js?ver=0.9'></script>

In your WordPress POST you can now easily run any function defined in slider.js : 
<script>
start_slider();
</script>

Reference