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:
- We want to use standard WP methods, so that other plugins can do things like optimize or defer it
- We DON’T want it to load on every page.
- 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 Reply