How to use wp_enqueue_script() in WordPress

wp_enqueue_script() is a WordPress function used to register and enqueue JavaScript files into WordPress. This function ensures that JavaScript files are loaded in the correct order, and only when they are needed. Here’s how to use it:

  1. Register the script:
php
function my_enqueue_script() {
wp_register_script( 'my-script', get_template_directory_uri() . '/js/my-script.js', array(), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_script' );

This code registers a script called my-script, which is located in the js directory of the current theme, with a version number of 1.0. The last parameter true means that the script should be loaded in the footer.

  1. Enqueue the script:
php
function my_enqueue_script() {
wp_register_script( 'my-script', get_template_directory_uri() . '/js/my-script.js', array(), '1.0', true );
wp_enqueue_script( 'my-script' );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_script' );

This code enqueues the my-script script that we registered in step 1. The script will now be loaded in the header or footer of the WordPress site, depending on the value of the last parameter.

You can also enqueue scripts from external sources, such as a CDN:

php
function my_enqueue_script() {
wp_enqueue_script( 'jquery', 'https://code.jquery.com/jquery-3.6.0.min.js', array(), '3.6.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_script' );

This code enqueues the jQuery library from the jQuery CDN.

Note: wp_enqueue_script() should be used within the wp_enqueue_scripts action hook to ensure that scripts are loaded correctly.