, ,

How to Enqueue JavaScript for a Shortcode

Are shortcodes still a thing? Sure WordPress has moved to the block editor, making those bracketed little buddies feel like a relic of the past. Even the block editor that I’m typing in now wants to autocorrect ‘shortcode’ into ‘shortcake’. That being said, I still find my self using shortcodes, especially on legacy sites that aren’t ready to migrate thousands of posts into Gutenberg.

One of the top questions I get is how to add JavaScript into your shortcode. The main goals are:

  1. We want to use standard WP methods, so that other plugins can do things like optimize or defer it
  2. We DON’T want it to load on every page.
  3. We may want it to load BEFORE content is rendered, meaning we don’t just want to inject a script tag into the middle of the page.

Here’s what I’ve been doing:

The main idea here is that we load the javascript in our normal wp_enqueue_scripts action, but we first check to see if the post content has our shortcode. Makes sense, right?

Learn Modern WordPress Development

I’m sharing the best resources and tutorials for developers building in and on the block editor.


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.