In this article, we will learn how to enqueue style and script in WordPress.
We will start by enqueue using two functions wp_enqueue_style() and wp_enqueue_script(). Both the two functions have the first 4 parameters that are the same and the last one is different.
syntax:
wp_enqueue_style( string $handle, string $src = '', array $deps = array(), string|bool|null $ver = false, string $media = 'all' ) wp_enqueue_script( string $handle, string $src = '', array $deps = array(), string|bool|null $ver = false, bool $in_footer = false )
Explanation:
- $handle : (string) (Required) Name of the stylesheet. Should be unique.
- $src: (string) (Optional) Full URL of the stylesheet, or path of the stylesheet.
- $deps: (array) (Optional) An array of registered stylesheet handles this stylesheet depends on.
Default value: array() - $ver: (Optional)
- String: specifying stylesheet version number.
- Bool: If the version is set to false, a version number is automatically added equal to the current installed WordPress version.
- Null: no version is added.
- $media: (Optional)
string: 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’ - $in_footer: This parameter is only available for scripts. If set to true the script is loaded through wp_footer() at the bottom of your page.
Default value: false
Here is an example code:
- put this below function in your theme’s functions.php.
-
<?php function thecodehubs_enqueue_script_style() { wp_enqueue_style( 'stylesheet', get_stylesheet_directory_uri() . '/style.css', array(), '1.0.0', 'all'); wp_enqueue_script( 'custom_js', get_stylesheet_directory_uri() . '/js/custom.js', array(), '1.0.0', true ); } add_action( 'wp_enqueue_scripts', 'thecodehubs_enqueue_script_style' ); ?>
Output:
style.css
custom.js
if you want to enqueue style and script for administration panel then use add_action( ‘admin_enqueue_scripts’, ‘thecodehubs_enqueue_script_style’ );