Blog

How to add CSS or JS to your WordPress site

Posted on: 27 December 2015     Posted by: Freesize Workroom

Use  wp_enqueue_script() function to enqueue CSS or JS scripts. Read here for more details.

 

The following example will enqueue the JS script of jQuery Cycle 2 to footer of the WordPress site.  (Add the code below to function.php)


function queue_cycle() {
   if ( is_page_template( 'home.php' ) ) {
      wp_enqueue_script(
         'enquirejs', //specify a name for the script 
         get_stylesheet_directory_uri() . '/js/vendor/jquery.cycle2.min.js', //url to css or js script
         array(), //add in script dependency here
         '2.1.2', //version no. for the script
         true //set to true will insert script to the footer, false to insert script into the header
      );
   }
}

add_action( 'wp_enqueue_scripts', 'queue_cycle');

 

If you need enqueue the script on a specific page, simply use the conditional tag.

The example below will enqueue the JS script of jQuery Cycle 2 on the home page. (Add the code below to function.php)


function queue_cycle() {
   if ( is_page_template( 'home.php' ) ) {
      if ( is_home() ) { //check if the current location is home page, and then enqueue the script below
         wp_enqueue_script(
            'enquirejs', //specify a name for the script 
            get_stylesheet_directory_uri() . '/js/vendor/jquery.cycle2.min.js', //url to css or js script
            array(), //add in script dependency here
            '2.1.2', //version no. for the script
            true //set to true will insert script to the footer, false to insert script into the header
         );
      }
   }
}

add_action( 'wp_enqueue_scripts', 'queue_cycle');