How can I enqueue custom scripts correctly in WordPress?
Asked on Oct 18, 2025
Answer
To enqueue custom scripts correctly in WordPress, you should use the `wp_enqueue_script` function within a hook. This ensures that your scripts are loaded in the right order and only when needed. Typically, this is done within the `functions.php` file of your theme.
<!-- BEGIN COPY / PASTE -->
function my_custom_scripts() {
wp_enqueue_script('my-script', get_template_directory_uri() . '/js/my-script.js', array('jquery'), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'my_custom_scripts');
<!-- END COPY / PASTE -->Additional Comment:
- The `wp_enqueue_script` function takes several parameters: the handle name, the script source, dependencies, version number, and whether to load it in the footer.
- Using `wp_enqueue_scripts` action ensures your scripts are added at the correct time during the page load.
- Always use `get_template_directory_uri()` or `get_stylesheet_directory_uri()` to correctly reference your theme's directory.
Recommended Links: