Add Custom CSS and JavaScript in WordPress

When creating your own WordPress theme, at some point you’ll need to add stylesheet and other functionality to tailor the website to your needs. There is an existing style.css file which is required in all themes, but it may be necessary to add other files to extend the functionality of your theme. To add custom CSS and JavaScript in WordPress, you will need to amend your theme’s functions.php file.

This file is responsible for defining functions, classes, actions and filters that will be used by other templates in the theme. This is the preferred and proper way of adding assets in WordPress, rather then loading the stylesheet in the theme’s header.php file.

Within this file, functions are created that will enqueue all of your scripts and styles. The inbuilt WordPress functions that do this can also enqueue scripts that might have dependencies on others, such as jQuery plugins that depend on jQuery.

To add stylesheets, create a function within functions.php, and within this defined function, use the wp_enqueue_style() in-built WordPress function.

function theme_styles() {
    wp_enqueue_style( 'custom_css', get_theme_file_uri('/assets/css/custom-styles.css' ) );
    wp_enqueue_style('bootstrap_css', '') );

add_action( 'wp_enqueue_scripts', 'theme_styles');

wp_enqueue_styles() can take up to five parameters.

  • $handle – The name of the stylesheet.
  • $src – Where the stylesheet is located.
  • $deps – An array. Whether or not this stylesheet is dependent on another stylesheet. If this is set, this stylesheet will not be loaded unless its dependent stylesheet is loaded first.
  • $ver – Sets the version number.
  • $media – Specifies which type of media to load this stylesheet in, such as all, screen, print or handheld.

Similarly to add JavaScript, create a function within functions.php, and within this defined function, use the wp_enqueue_script() in-built WordPress function.

function theme_js() {
    wp_enqueue_script( 'bootstrap_js', '', array('jquery'));
    wp_enqueue_script('flexslider_js', get_theme_file_uri('/assets/js/jquery.flexslider-min.js') );
add_action( 'wp_enqueue_scripts', 'theme_js');

The wp_enqueue_script() function, like wp_enqueue_styles(), can take up to five parameters.

The first four parameters are identical to the CSS function, however the fifth, $in_footer, is a boolean parameter that allows you to place your scripts in the footer of your HTML document rather then in the header.

Note: This article is based on WordPress version 4.9.