WordPress Enqueue CSS and JS Files
- JS and CSS files should be loaded into a template file using the
wp_enqueue_script()
andwp_enqueue_style()
functions from the themesfunctions.php
file. - Do not write link tags in the
header.php
template file. Enqueued files are pulled-in with thewp_head()
template function. - Enqueuing ensures proper loading and caching, and allows the use of conditional tags to target specific pages.
- Including CSS and Javascript (developer.wordpress.org)
- wp_enqueue_style() (developer.wordpress.org)
- wp_enqueue_script() (developer.wordpress.org)
- https://developer.wordpress.org/themes/basics/including-css-javascript/
wp_enqueue_style()
Enqueue styles with wp_enqueue_style()
:
wp_enqueue_style( $handle, $src, $deps, $ver, $media );
Parameter | Description |
---|---|
$handle |
(string) (Required) Name of the stylesheet. Should be unique. |
$src |
(string) (Optional) Full URL of the stylesheet, or path of the stylesheet relative to the WordPress root directory. Default value: “ |
$deps |
(string[]) (Optional) An array of registered stylesheet handles this stylesheet depends on. Default value: array() |
$ver |
(string|bool|null) (Optional) String specifying stylesheet version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version. If set to null, no version is added. Default value: false . |
$media |
(string) (Optional) The media for which this stylesheet has been defined. Accepts media types like ‘all’, ‘print’ and ‘screen’, or media queries like ‘(orientation: portrait)’ and ‘(max-width: 640px)’. Default value: all |
function add_theme_scripts() {
wp_enqueue_style('my-styles', get_template_directory_uri() . '/css/my-styles.css', array('css-reset'), '1.1', 'all');
}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );
wp_enqueue_script()
Enqueue scripts with wp_enqueue_script()
.
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer);
Parameter | Description |
---|---|
$handle |
(string) (Required) Name of the script. Should be unique. |
$src |
(string) (Optional) Full URL of the script, or path of the script relative to the WordPress root directory. Default value: “ |
$deps |
(string[]) (Optional) An array of registered script handles this script depends on. Default value: array() |
$ver |
(string|bool|null) (Optional) String specifying script version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version. If set to null, no version is added. Default value: false |
$in_footer |
(bool) (Optional) Whether to enqueue the script before |