WordPress: Including CSS & JavaScript

While you are developing WordPress theme, you may want to add custom stylesheets or javascript files. Before we just start adding stylesheets or javascript files, therefore it’s important to keep in mind that WP is also loading CSS & JS fiels of other plugins.

In order to make it sure that everything workds harmoniously, we should use the standard WordPress method to load theme, plugins scripts and stylesheets.

Adding aditianal scripts and stylesheets to the WordPress is failry simple process. Principally you will create a funciton that will enqueue all the scripts and styles.

By using WordPress hook, it will find the required resources, let’s look at how to do so.

Enqueuing Scripts and Styles

The official way of adding scripts & styles to any theme is to enqueue them in the “functions.php” files using wp_enqueue_script(); or wp_enqueue_style(); methods.

Let’s take a look at the enqueue basic usage, to enqueue style.css.

wp_enqueue_style( 'style', get_stylesheet_uri() );

This will look for a stylesheet named โ€œstyleโ€ and load it.

If you wish to load CSS or JS file from the specific path, following methed will come in to use.

 wp_enqueue_style('mysite_main_styles', get_theme_file_uri('/build/index.css'));

And in case you want to add files from a public url like wise fontawesome, take a look at following line of code:

wp_enqueue_style('font-awesome','//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css');

Enqueue your script:

wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer);

The enqueue function may look like this:

wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), 1.1, true);

This is very basic and quite simple implementation, when you are developing custom themes.

Author: Danyal
I'm a skilled programmer specializing in Vue.js/Nuxt.js for front-end development and PHP Laravel for back-end solutions. I have a strong focus on API design and development, complemented by experience in web server setup and maintenance. My versatile expertise ensures seamless creation and maintenance of web applications, covering everything from intuitive user interfaces to robust server-side functionality. Passionate about coding and driven by a lifelong learning mindset, I invite you to explore more at danyal.dk.