How to include CSS and JS files in WordPress

WordPress 2 minutes read

The recommended way to include CSS and JS files in WordPress is by using the wp_enqueue_style() and wp_enqueue_script() functions respectively. These functions allow you to register and enqueue your files in the correct order and location, ensuring that your styles and scripts are loaded correctly and efficiently.

Here’s an example of how you can enqueue a CSS file in your WordPress theme’s functions.php file:

function mytheme_enqueue_styles() {
    wp_enqueue_style( 'mytheme-style', get_stylesheet_uri() );
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_styles' );

And here’s an example of how you can enqueue a JS file and pass variables from PHP to it:

function mytheme_enqueue_scripts() {
    wp_enqueue_script( 'mytheme-script', get_template_directory_uri() . '/js/my-script.js', array( 'jquery' ), '1.0.0', true );

    // Localize the script with some data
    $data = array(
        'foo' => 'bar',
        'baz' => 'qux'
    wp_localize_script( 'mytheme-script', 'my_data', $data );
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_scripts' );

In the example above, we’re using the wp_localize_script() function to pass a PHP array to our my-script.js file. We’re also using the true parameter in wp_enqueue_script() to ensure that our script is loaded in the footer after the page content has loaded.

In our JS file, we can then access this data using the my_data object, like so:

console.log(; // outputs 'bar'
console.log(my_data.baz); // outputs 'qux'
Was this article helpful?

Add comment