How to Add Scripts and Stylesheets in WordPress – Imtiaz Rayhan

WordPress provides wp_enqueue_script and wp_enqueue_style function to add Scripts and Stylesheets in a systematic way.

If you’re wondering why you should use these functions when you can simply load them in header or footer, here’s why – by adding JavaScripts that way, you increase the chance of conflicting with other scripts.

Also, If we add our script directly to header, then it will load on every page, even if we don’t need it to. That’ll cause slow page loading.

By using wp_enqueue_script function we can tell WordPress when to load a script, where to load it and what are its dependencies. We can even determine whether the scripts should load in footer or header.

How to Enqueue Scripts in WordPress

Now, let’s see how to use wp_enqueue_script to add scripts in WordPress. Check the following code.

<?php

function script_register () {

//Enqueuing scripts
 wp_enqueue_script('jquery');
 wp_enqueue_script('mycustom-js', get_template_directory_uri() . '/js/script.js', 
 array(jquery), '1.2', true);

}
//Adding scripts
 add_action ('wp_enqueue_scripts', 'script_register');

?>

Let me explain this to you. wp_enqueue_script accepts five parameters. These are –

Then, We used the wp_enqueue_scripts action hook to add the script to WordPress. If you don’t know add_action() function, here the first parameter is the action and the second parameter is the function to which the action is added.

How to Enqueue Stylesheets in WordPress

Now let’s check how we can enqueue our stylesheets in WordPress using the wp_enqueue_style function. Check the following code.

<?php

function stylesheet_register () {

//Enqueueing stylesheet
  wp_enqueue_style('mystyle', get_stylesheet_uri());
  wp_enqueue_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', 
  array('mystyle'), '1.2', 'all');

}

//Adding Stylesheet
  add_action('wp_enqueue_scripts', 'stylesheet_register');

?>

This is similar to the wp_enqueue_script function. wp_enqueue_style also accepts five parameters.

Just like before, we used wp_enqueue_scripts action hook to load our stylesheet.

Notice, how we used wp_enqueue_scripts action hook for both scripts and stylesheets. Despite the name, it works for both.

How To Enqueue Stylesheets and Scripts in WordPress Admin

Adding stylesheets and scripts to WP admin pages is almost same. Only difference is the hook used. Previously, we used wp_enqueue_scripts hook. Now we will use admin_enqueue_scripts hook.

<?php

function script_register () {

 wp_enqueue_script('jquery');
 wp_enqueue_script('mycustom-js', get_template_directory_uri() . '/js/script.js', 
 array(jquery), '1.2', true);

}

add_action ('admin_enqueue_scripts', 'script_register');

?>

I hope this post helped you to understand how to add your scripts and stylesheets in WordPress. If you have any queries, let me know through comments.

This content was originally published here.