At the moment, there is no way to query posts in WordPress based on the condition of having or not having a shortcode. There’s no way to grab all posts with galleries. All posts with embedded audio/video. All posts with legacy shortcodes in need of an upgrade.
Well, you can create a new
WP_Query instance and pass part of the shortcode in as a search parameter. You can create a custom SQL query to match against the content of posts.
Both of these solutions are hacks; non-performant hacks at that! 1
I ran head-first into this issue last week when I needed to query the database for all posts containing a
gallery tag. The solution turned out to be a hook on WordPress’ save action that flags the post as having or not having a gallery in a hidden “flags” taxonomy.
My proposal – make this part of WordPress core.
Every shortcode tag would become a term in a “shortcode” taxonomy. On save, posts will be automatically tagged with whatever shortcodes their content happens to contain. Queries then become simple:
Does it Make Sense for Core?
The first argument against this change would be “this sounds like plugin material.” On one hand, I agree. Building a flags taxonomy for your theme or plugin to keep track of shortcodes in use is, ultimately, a simple endeavor. Actually, I’ve already written the code for it.
The argument to have this functionality in core, however, is a simple one: Standardization. By having this code in core by default, all shortcodes will be tracked whether they’re in core, in a plugin, or in the theme. Plugins and themes can then query against a standard taxonomy to find shortcodes in use.
Ultimately, it’s an argument for interoperability between shortcodes among plugin and theme developers. Does this argument mean it makes sense for core? I say yes. What do you think?