Shortcodes are pretty cool, and the do_shortcode function is pretty neat as it can parse and execute shortcode callbacks from arbitrary strings, but that function invokes a fairly large regex every time it is called.
That regex looks for all registered shortcodes within a string. For each match, it runs a replacement with a callback function, which also take the time to parse the shortcode attributes, before finally calling the actual callback function that’s been registered with add_shortcode
.
Regular expressions are pretty fast in PHP, especially for short strings, but do we really have to have WordPress do all that extra work, when all we really intended was to call our shortcode callback function?
echo do_shortcode( '[foo]' ); // Boo echo foo_shortcode_callback(); // Yey!
I ran a quick search in the plugins directory, using the following regex:
do_shortcode\(\s*['"]\[
Not the best crafted regex, but it’s supposed to look for calls to do_shortcode
followed by a string literal starting with an opening square bracket. Obviously it might get a few false positives for special cases, but it also misses quite a few matches where the shortcode string is put into a variable first.
I found over 600 entries in over 270 plugins, including some of my own. Guilty! So the lesson I learned today is: don’t use do_shortcode
when you can use your callback function directly, which is much more efficient.