WordPress Code Snippets

A fresh mix of code snippets and tutorials

WordPress Conditional Do Shortcode


Quick snippet to call and evaluate WordPress shortcodes conditionally, outside of their normal Post/Page context.

If you are working with shortcodes outside of the normal context (e.g., post content), you’ll find that they are not by default parsed by WordPress. This makes it challenging to evaluate the shortcode and execute conditional logic. The following snippet illustrates a solution via get_shortcode_regex().

In many cases where we need to call a shortcode outside of Post and Page context, we can simply use do_shortcode() and call it a day. This example goes a step further and checks the content, $message, to see if the shortcode exists in the first place. If so then do_shortcode() is used to grab the shortcode output as a variable for later use.

FWIW, I use a variation of this snippet in my plugin, SES Pro, in order to parse various shortcodes in Ajax-loaded content. I posted another example of this technique in WordPress Conditional Shortcodes via Ajax.


Learn more

WordPress Themes In Depth

Show Support

Like our new Facebook Page to show support!