How to enqueue scripts and style sheets in WordPress

If you want to add scripts and styles into your WordPress installation, there are different ways of doing the same. Because some are dated and some might cause conflicts if you install numerous plugins, we are going to show you the right way to add those scripts and styles in your WP – you will enqueue them.

For example, you might want to use a jQuery code to create a toggle effect in your articles. You might have the code, but if you don’t load scripts into your header, the code simply won’t work.

There isn’t much to know about it if you only want to make everything work. To enqueue scripts added to the header, copy and paste the following code into your plugin or your functions.php file.

The part you are interested in is   wp_enqueue_script() where you only have to point to the file where your code is located. In the example below, you can see that we used the function which enqueues “faq-toggle.js” file which we had been created in toggle shortcode article.

If you are using the enqueue technique to load other scripts, simply change the name and the location of the file and you’re ready to go.

Enqueue scripts:

<?php
function wpb_adding_scripts() {
wp_register_script('faq-toggle', plugins_url('faq-toggle.js', __FILE__), array('jquery'),'1.1', true);
wp_enqueue_script('faq-toggle');
}

add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
?>

Enqueue CSS files:

To enqueue .css file, you will do the same. Copy and paste the following code in functions.php file:

<?php
function wpb_adding_styles() {
wp_register_script('my_stylesheet', plugins_url('my-stylesheet.css', __FILE__));
wp_enqueue_script('my_stylesheet');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_styles' );
?>

If you’re working on your child theme, you should use get_stylesheet_directory_uri() instead the template one.

And that’s it. Now you know how to properly load scripts and styles into your WordPress.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

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