Enqueue scripts on the WordPress front end and login page

This post is more than 6 years old.

If you want to load a script or stylesheet on both the WordPress front end and login page, here’s how to register it once and load it in the appropriate places.

The WordPress reference manual tells us that scripts should not be enqueued before the wp_enqueue_scripts hook. But that’s not quite accurate; scripts and stylesheets can be safely registered and enqueued after the init hook. This becomes important when we want to register the details of a script or stylesheet once, and reuse it in different places on different action hooks:

  • the front end, via the wp_enqueue_scripts hook
  • the login page, via the login_enqueue_scripts hook
  • the admin, via the admin_enqueue_scripts hook
  • on selected front end pages when a shortcode is rendered

In order to register our asset once and be able to access it in all of those instances, we need to register it on the init hook. It can then be enqueued in any circumstance that allows enqueuing scripts and stylesheets.

Here’s some sample code for registering a script once and loading it on the front end and the login page. It has a couple of other niceties, like switching between the full and minified version based on the SCRIPT_DEBUG constant, and forcing a cache buster when SCRIPT_DEBUG is true.

// declare the script version, e.g. theme version
define('EXAMPLE_SCRIPT_VERSION', '1.2.3');

/**
* register scripts on the init action, for use anywhere
*/
add_action('init', function() {
    $theme_dir = get_stylesheet_directory_uri();
    $min = SCRIPT_DEBUG ? ''     : '.min';
    $ver = SCRIPT_DEBUG ? time() : EXAMPLE_SCRIPT_VERSION;

    wp_register_script('example', "$theme_dir/js/example$min.js", ['jquery'], $ver, true);
});

/**
* load scripts and styles on the front end
*/
add_action('wp_enqueue_scripts', function() {
    $theme_dir = get_stylesheet_directory_uri();
    $min = SCRIPT_DEBUG ? ''     : '.min';
    $ver = SCRIPT_DEBUG ? time() : EXAMPLE_SCRIPT_VERSION;

    wp_enqueue_script('example');
	wp_enqueue_style('example-front', "$theme_dir/css/front$min.css", [], $ver);
});

/**
* load scripts and styles on the login page
*/
add_action('login_enqueue_scripts', function() {
    $theme_dir = get_stylesheet_directory_uri();
    $min = SCRIPT_DEBUG ? ''     : '.min';
    $ver = SCRIPT_DEBUG ? time() : EXAMPLE_SCRIPT_VERSION;

    wp_enqueue_script('example');
	wp_enqueue_style('example-login', "$theme_dir/css/login$min.css", [], $ver);
});

Register once, load whenever. Job is done.