WP-Mix

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().

$unsub = '';
$pattern = get_shortcode_regex();
if (preg_match('/'. $pattern .'/s', $message, $matches) && array_key_exists(2, $matches)) {
	if ($matches[2] == 'ses_unsubscribe') {
		$unsub = do_shortcode($matches[0]);
	}
}

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.

References

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress