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

How can I safely enqueue scripts and styles in a WordPress theme?

Asked on Aug 24, 2025

Answer

In WordPress, safely enqueuing scripts and styles is essential for ensuring that assets are loaded correctly and without conflicts. This is typically done using the `wp_enqueue_script` and `wp_enqueue_style` functions within the `functions.php` file of your theme.
<!-- BEGIN COPY / PASTE -->
    function my_theme_enqueue_scripts() {
        // Enqueue a stylesheet
        wp_enqueue_style('my-theme-style', get_stylesheet_uri());

        // Enqueue a script with jQuery as a dependency
        wp_enqueue_script('my-theme-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery'), null, true);
    }
    add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');
    <!-- END COPY / PASTE -->
Additional Comment:
  • Use `wp_enqueue_scripts` action to enqueue both scripts and styles properly.
  • Always provide a unique handle for each script or style to avoid conflicts.
  • Use `get_stylesheet_uri()` for the main stylesheet of a theme.
  • Specify dependencies in the third parameter of `wp_enqueue_script` to ensure scripts load in the correct order.
  • Set the last parameter of `wp_enqueue_script` to `true` to load scripts in the footer, improving page load times.
✅ Answered with WordPress best practices.

← Back to All Questions
The Q&A Network