Enqueue script only when shortcode is used, with WP Plugin Boilerplate

Why it’s not working:

You need to use the wp_enqueue_scripts action hook. You’ve used wp_register_script as an action hook, however, there is no action hook named wp_register_script in WordPress core.

If this was just a silly mistake, then you already have the answer. Read on if you need more information regarding the topic:


Attaching a callback function to wp_enqueue_scripts action hook doesn’t mean your scripts and styles will be enqueued, it simply means when you want to execute that callback function.

The original registering and enqueuing is done by functions such as: wp_register_script(), wp_register_style, wp_enqueue_script(), wp_enqueue_style() etc., not by any hook.

Note the difference between the role of functions and hooks:

  • A function executes some CODE to accomplish predefined tasks when called.

    Example: these all are WordPress core functions: wp_register_script(), wp_register_style, wp_enqueue_script(), wp_enqueue_style().

  • A hook only attaches a callable function (to be executed later) at a predefined point of CODE execution.

    Example: this is a WordPress core (action) hook: wp_enqueue_scripts – notice the s (plural) at the end.

    Double check: wp_enqueue_script() is a function and wp_enqueue_scripts is an action hook.

The correct CODE:

So your corrected CODE should be like:

private function define_public_hooks() {
    // ...
    $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'register_styles' );
    $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'register_scripts' );
    // ...
}

Then,

public function register_scripts() {
    wp_register_script( $this->plugin_name . '_google_maps_api', '//maps.googleapis.com/maps/api/js?key='. $gmap_key.'&v=3&libraries=places', array( 'jquery' ), '3', true );
}

After that, you enqueue the script (& style) from within you shortcode handler function:

public function your_shortcode_handler( $atts ) {
    // shortcode related CODE
    wp_enqueue_script( $this->plugin_name . '_google_maps_api' );
    // more shortcode related CODE
}

With this CODE, your scripts / styles enqueued from your_shortcode_handler function will only be added to your site when there is a shortcode in that particular URL.

Further Reading:

This answer has an interesting discussion on enqueuing scripts & styles only when shortcode is present.

Leave a Comment