WordPress: Adding CSS or JS to a Template
At Y-Designs, we recommend making separate CSS and JS files for different templates within your website. Compiling all styling and scripts can cause slower load times and confusion when editing your website. Below I show you how to add CSS and JS files to your WordPress template.
Once you have created a new CSS or JS file, go to the template you want to add the files to. At the top of your page add the two general structures for CSS and JS displayed below.
Add CSS to Your WordPress Template
<?php wp_enqueue_style( $handle, $src, $deps, $ver, $media ); ?>
ex.
<?php wp_enqueue_style('home', get_stylesheet_directory_uri().'/css/pages/home.css',array('style')); ?>
Add JS to Your WordPress Template
<?php wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer ); ?>
ex.
<?php wp_enqueue_script('home', get_stylesheet_directory_uri().'/js/pages/home.js', array('bootstrap'), '1',true); ?>
Parameters
The parameters for each are displayed below.
$handle – the name for your stylesheet or script. Keep these simple and straightforward (If it’s the Home page name it ‘home’).
$src – the URL to locate the stylesheet or script. get_stylesheet_directory_uri(). gets the WordPress theme’s root folder. From there link it to the CSS or JS file you wish (ex. ‘/css/pages/home.css‘).
$deps – This is an optional parameter. This is an array and tells what CSS or JS files the file depends on. Therefore, array(‘style’) will load the CSS file named “style” before and array(‘style, products’) will load the CSS files named “style” and “products” before.
$ver – This is an optional parameter. This is the version number so that the correct version of the stylesheet or script is loaded.
$in_footer – (for JS only) This is an optional parameter. This is a boolean (true or false) and specifies where the script will be placed. If it is set to true, the script is placed before the </body> end tag. It is set to false by default.
$media – (for JS only) This is an optional parameter. This specifies the stylesheet’s media. it’s set to “all” by default, so unless you need to specify the media type, there is no need to define this parameter. Other options include: ‘all’, ‘screen’, ‘handheld’, ‘print’.