WP: Enqueue Styles & Scripts

To Enqueue styles and scripts in WordPress, we add some piece of code in our theme’s functions.php file.

We’ve enqueued style.css in the previous post using wp_enqueue_style function. Let’s enqueue a script now and see how that’s done.

I have changed the functions.php code to the following:

<?php 

function ob_site_files() {
	wp_enqueue_style('ob_site_main_styles', get_stylesheet_uri());
	wp_enqueue_script('ob_site_main_script', get_theme_file_uri('/js/script.js'), NULL, '1.0', true);
	wp_enqueue_style('font-awesome', '//stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css');
}
add_action('wp_enqueue_scripts', 'ob_site_files');

To recap – We enqueue specific “style” and “script” by loading our function ob_site_files (which is triggered by an in-built WordPress action called wp_enqueue_scripts).

Line 5 and 6 are new in the code above.

Line 5 adds a script using wp_enqueue_script function that accepts (1) script name, (2) script URI, (3) dependencies, (4) version number and (5) a boolean argument which tells whether to enqueue the script before </body> instead of in the <head> (true loads it before the end of body tag).

Line 6 loads an external stylesheet (font-awesome). Note that we’re not adding any protocol (http or https) in there because wp_enqueue_style function will take care of that for us.

That’s how we enqueue styles and scripts the WordPress way.