How to add Scripts through Hooks in WordPress

Most of the newbies adding styles and scripts directly. But that is not a good practice to adding styles to the WordPress directly. You can simply add styles to WordPress via functions.php file. Lets see how to do that.

First you need to create function in functions.php file.

I am defining my function as function nero_resources() {}

Then you need to enqueue the function as add_action( ‘wp_enqueue_scripts’, ‘nero_resources’ );

To register a stylesheet, there are five parameters we can use. Out of five two parameters are required and other three are optional. Will discuss the required parameters one by one.

$handle

This is the name of the stylesheet and has no default value. We must define this value as it hasn’t any default value. As well it is better to add a prefix for the handle. Assume you are going to add Bootstrap style and you can name the handle as ‘bootstrap’. This is fine but I suggest you use a prefix. For example ‘nero_bootstrap’. This will make you a unique stylesheet.

$src

Path to the Stylesheet referring $src. This is also required and you can use either remote assets or assets from the development. Either Plugin or a Theme. For themes use get_template_directory_uri() for theme directory reference and use plugins_url() for plugin.

These two are the required when you are registering a stylesheet. Lets register bootstrap style for our theme.

wp_register_script( ‘nero_bootstrap’, get_template_directory_uri() . ‘/path/to/bootstrap.js’ );

This will register bootstrap stylesheet. Once we have registered our stylesheet then we need to enqueue it to the WordPress. For that you need to use one simple line of code as follow.

wp_enqueue_scripts( ‘nero_bootstrap’ );

Now your whole function should look like this.

function nero_resources() {

wp_register_script( ‘nero_bootstrap’, get_template_directory_uri() . ‘/path/to/bootstrap.js’ );

wp_enqueue_scripts( ‘nero_bootstrap’ );

}

add_action( ‘wp_enqueue_scripts’, ‘nero_resources’ );
function nero_resources() {

wp_register_script( ‘nero_bootstrap’, get_template_directory_uri() . ‘/path/to/bootstrap.js’ );

wp_enqueue_scripts( ‘nero_bootstrap’ );

}

add_action( ‘wp_enqueue_scripts’, ‘nero_resources’ );
Instead of two processes you can use this in same line. such as

wp_enqueue_script( ‘nero_bootstrap’, get_template_directory_uri() . ‘/path/to/bootstrap.js’ );
1
wp_enqueue_script( ‘nero_bootstrap’, get_template_directory_uri() . ‘/path/to/bootstrap.js’ );
This is also fine and working great. But I am highly recommending the first register then enqueue. That is the best way recommending.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *