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 skilled programmer with expertise in Vue.js/Nux.js for front-end development and PHP Laravel for back-end development. I excel in building APIs and services, and also have experience in web server setup & maintenance. My versatile skill set allows you to develop and maintain web applications effectively, from the user interface to the server-side functionality. I love coding with never ending learning attitude, thanks for visiting danya.dk