How to add JavaScript’s

Usually Script files adding to the end of files instead of loading JS in head. Before adding scripts we need to call a WordPress function in footer. Just before the closing body tag add this code. Lets move onto adding scripts.

Open up function file and inside the function we defined nero_resources() add following code.

wp_enqueue_script( 'jquery' );

jQuery is coming up with WordPress. So, we do not need to add our versions of jQuery. That is not the best way. The best way is use the jQuery which is come up with WordPress by default. For that just enqueuing is enough. No need to register because it is already there.

But there are some scripts we need to register for our theme. Because they are our own and only for this theme. Lets register Bootstrap. For that you need to use

wp_register_script ( 'bootstrap-script', get_template_directory_uri() . '/js/bootstrap.js', array ( 'jquery' ), false, true );

This function is same as the wp_register_style(). This function also has five parameters. first two are required and last three are optional.

$handle – Script name

$src – Path to the file

$deps – Dependencies for the script. Should define as array list

$ver – Version of the Script

$in_footer – Need to show in footer ? True or False

Lets see the registered script with these parameters. Keep in mind that we have already enqueued jQuery. Now you should aware about the first parameter value ‘bootstrap-script’. This is the name of the script. Next is the source to the file. That should also be fine. Next the third parameter there is a array defined and inside that value jquery is passed. It is because bootstrap runs depends on jquery. We have created dependency for bootstrap. And also we haven’t passed any version number in fourth parameter and finally we have asked WordPress to load this Bootstrap file in footer.

Finally we need to enqueue this registered Bootstrap Script. For that add following code.

wp_enqueue_script( 'bootstrap-script' );

Now complete function after adding Styles and Scripts should see as the following.

function nero_resources() {
    wp_register_style( 'nero_bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css' );
    wp_register_style( 'nero_style', get_stylesheet_uri() );
    wp_enqueue_script( 'nero_bootstrap' );
    wp_enqueue_script( 'nero_style' );
    wp_register_script ( 'bootstrap-script', get_template_directory_uri() . '/js/bootstrap.js', array ( 'jquery' ), false, true );
	wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'bootstrap-script' );
add_action( 'wp_enqueue_scripts', 'nero_resources' );

You may also like...

Leave a Reply

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