Enqueue CSS and JavaScript on WordPress

I recently learned that I have been adding CSS stylesheets and JavaScript on to my WordPress themes the wrong way. Since I started developing websites in HTML a couple of years ago, I’ve been used to adding all styles and scipts in the header, as I learned how to. Naturally, when I transitioned to developing websites on WordPress, I would simply copy and paste the code into the header.php – as I learned via basic tutorials online. Well, that’s not the best way, or a good way in general, to do it. We need to make proper use of WordPress’ enqueue function.

<head>
	<link rel="stylesheet" href="<?php echo get_stylesheet_uri(); ?>">
</head>

It works fine that way, but it’s a terrible practice that needs to be stopped. The problem is that loading the styles and scripts in the header may cause unnecessary duplication between other sources such as plugins that depend on certain styles or scripts.

For example, if plugin A loads jQuery manually and plugin B loads a different version of jQuery manually, it’s possible that these two different version would conflict against each other and could potentially stop working overall.

Enqueue styles and scripts

Enqueueing tells WordPress about the assets that need to be added and it will link them in the header and footer. The code below is an example of what you would need to paste into your functions.php, a plugin file or a child theme.

/* Enqueue styles */
function my_scripts() {
	wp_enqueue_style('style', get_stylesheet_uri() );
	wp_enqueue_script('jquery');
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
?>

Both styles and scripts are registered using the wp_enqueue_style() function. The first wp_enqueue_style() adds the theme’s style.css while the second one loads up WordPress’ version of jQuery. You can also use wp_enqueue_style() to load styles and scripts on different directories or hosted on CDN’s.

/* Enqueue styles */
function my_scripts() {
	wp_enqueue_style( 'normalize', get_template_directory_uri() . '/css/normalize.css' ); 
	wp_enqueue_style( 'roboto', '//fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,700,700italic' ); 
	wp_enqueue_style( 'bootstrap', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' );
	wp_enqueue_style( 'font-awesome', '//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css' );
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
?>

Hope this helps you as much as it helped me. I’m still in the early stages of web development and am eager to keep learning new things along the way.

Leave a Reply

Your email address will not be published. Required fields are marked *