WordPress Q&As Logo
WordPress Q&As Part of the Q&A Network
Q&A Logo

How can I enqueue a custom script only for the homepage in WordPress?

Asked on Oct 27, 2025

Answer

To enqueue a custom script only for the homepage in WordPress, you can use the `wp_enqueue_scripts` action hook combined with a conditional tag to check if the current page is the homepage. This ensures that your script is loaded only when needed.
<!-- BEGIN COPY / PASTE -->
    function enqueue_custom_script_on_homepage() {
        if (is_front_page()) {
            wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', array(), '1.0', true);
        }
    }
    add_action('wp_enqueue_scripts', 'enqueue_custom_script_on_homepage');
    <!-- END COPY / PASTE -->
Additional Comment:
  • The `is_front_page()` function checks if the current page is the homepage.
  • Replace `'custom-script'` and the file path with your script's handle and location.
  • Ensure the script file exists in the specified directory to avoid loading errors.
  • Use `true` as the last parameter to load the script in the footer.
✅ Answered with WordPress best practices.

← Back to All Questions
The Q&A Network