Load your own .css and .js files into Wordpress

Objective#

Load one or more .js and/or .css files to create an animation or add a style effect.

Solution#

On a “non-wordpress” site we could include our scripts between the <head> tags of our HTML page.

With WordPress (3.X.X and 4.X.X) one of the possible solutions is to use the methods

  • _wp_enqueue_script_
  • _wp_enqueue_style_

of the function.php file.

Here is an example of code to include in the function.php file:

//Create a function to call javascript and css files
<?php function load_my_files() {   
  // Load files EXCEPT on site administration
  if (!is_admin()) {
    //Load js files
    wp_enqueue_script('script1', '/wp-content/themes/custom_theme/js/script1.js');
    wp_enqueue_script('script2', '/wp-content/themes/custom_theme/js/script2.js');
    //Load css files
    wp_enqueue_style('style2', '/wp-content/themes/custom_theme/css/style2.css');
    wp_enqueue_style('style1', '/wp-content/themes/custom_theme/css/style1.css');
      }
    }
    // Load our function on initialization
    add_action('init', 'load_my_files');
    ?>

Then place the .js and .css files on your server in the folders created for this purpose as in the example above