This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

Properly enqueuing script and styles in WordPress

Often when developing a site, plugin or theme you will want to enqueue your custom script or style, it is worth to learn how to do this right in order to avoid conflicts with third party plugins and decrease number of HTTP requests (for example avoid loading jQuery twice).

Without any further additions below is code that will load custom script and style in the frontend

add_filter("init", "stc_init");
function stc_init() {
    // first step is to register your custom scripts and styles, the scripts will be loaded
    // plugins_url() as used as below will work only when scripts are in the same directory
    // as *this* php file
    wp_register_script("stc-frontend-js", plugins_url("stc-frontend.js", __FILE__), array("jquery"));
    wp_register_style("stc-frontend-css", plugins_url("stc-frontend.css", __FILE__));

    // now we can localize the script (if needed)
    wp_localize_script("stc-frontend-js", "stc_frontend_js_lang", array(
        "hello_world" => __("Hello World!", "my-locale")
    ));
}

add_action("wp_enqueue_scripts", "stc_enqueue_scripts");
function stc_enqueue_scripts() {
    // the two lines below will load in <head> stc-frontend-js, stc-frontend-css
    // and jquery (since stc-frontend-js has dependency on jquery,
    // additionally stc_frontend_js_lang variable will be printend in page
    // html code ... so we are all set to use the scripts
    wp_enqueue_script("stc-frontend-js");
    wp_enqueue_style("stc-frontend-css");
}

Couple of things to consider

  • In order to get this to work you will need two files stc-frontend.js and stc-frontend.css in the same directory as the PHP code will be.
  • The scripts and styles will be loaded in <head> section, so in order to load them wp_enqueue_script and wp_enqueue_style functions have to be executed before head section is printend. Second possibility is to pass fourth (file version) and fifth arguments to wp_register_script, if you set the fifth argument to true then scripts will be loaded in footer instead.
  • This code is for loading resources in the frontend only if you want to do the same in wp-admin, then add following line at the end
    add_action("admin_enqueue_scripts", "stc_enqueue_scripts");
    

The complete source code for this snippet you can get from here.

About

Greg is a longtime WordPress enthusiast ho remembers the old days ... that is WP version 2.5. On a day to day basis he is lucky enough to work on various WordPress plugins. In the free time he blogs at wplingo.com.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.