Cheesetoast

Brain Food for Web Developers

Attach

Safely Include Scripts or Stylesheets In WordPress Header

There are a couple of ways to include files in your WordPress header. One way is to manually add the <script src=”…”></script> code to your header file. Although this works just fine, the recommended way to is use the WordPress function wp_enqueue_script() function.

Use this code in your functions.php file:

<?php 
add_action( 'wp_enqueue_scripts', 'add_custom_script' ); 
function add_custom_script() { 
   wp_enqueue_script( 
      'custom_slideshow_script',
      get_template_directory_uri() . '/js/custom-script.js',
      array('jquery') 
   ); 
}
add_action('wp_enqueue_scripts', 'add_custom_script');
?>

This particular use of the wp_enqueue_script function loads a script that is dependent on another WordPress script, in this case JQuery. There are several variations of this function that you can find on the WordPress Codex.

The function wp_enqueue_style can be used for stylesheets.

Author: Graham

My name is Graham and I'm a Scottish web developer living in California. I love working with clean code to make attractive and usable websites. I'm also interested in cooking, gardening, and taekwondo.

Comments are closed.