Skip to content

Enqueue – the correct way to add scripts and styles to WordPress websites

Enqueue – the correct way to add scripts and styles to WordPress websites

So you’re working on a WordPress theme or a plugin and you’re looking to include some stylesheets and Javascript files.

Don’t just inline the files, such as <link rel="stylesheet" href="/wp-content/themes/theme/style.css">That’s not the best approach.

You’ll need to enqueue the files. It’s all very simple.

All you need to do is create a function and then reference it in an action.

Code example:

<?php

    /**
     * Enqueue stylesheets and scripts, the proper WordPress way!
     * 
     * [1]  Add a stylesheet to your theme or plugin:
     *      [a] A unique name for the stylesheet, this allows it to be dequeued by other themes and plugins.
     *      [b] The path to the stylesheet (get_stylesheet_directory_uri() gets the directory of the theme).
     * 
     * [2]  Add a script to your theme or plugin:
     *      [a] A unique name for this script, this allows it to be dequeued by other themes and plugins.
     *      [b] The path to the script (get_stylesheet_directory_uri() gets the directory of the theme).
     *      [c] Define dependancies, in this case this script file requires jQuery.
     * 
     * [3]  Add an action for WordPress to add your files to the queue.
     */


    function mangopear__enqueue_files() {
        wp_enqueue_style('mangopear__global--styles', get_stylesheet_directory_uri().'/resources/css/compiled/screen.css'); // [1]
        wp_enqueue_script ('mangopear__global--scripts', get_stylesheet_directory_uri().'/resources/js/global.min.js', array('jquery')); // [2]
    }
    
    add_action('wp_enqueue_scripts', 'mangopear__enqueue_files'); // [3]

No comments

Add a comment

Start the conversation.
Be the first to comment.

Popular topics

On development

On best practice

On content strategy