How to Enqueue JS for a Shortcode

Posted in ,

Are shortcode’s 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 JS 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?

Leave a Comment





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