WP-Mix

A fresh mix of code snippets and tutorials

WordPress Conditional Shortcodes via Ajax

This example builds from the conditional do_shortcode technique to evaluate shortcodes during Ajax requests.

The following example illustrates use of get_shortcode_regex() to check if Ajax-loaded content includes the target shortcode, [ses_pro]. If it exists, we parse the shortcode attributes for later use in our script.

if (defined('DOING_AJAX') && DOING_AJAX) {
	if (isset($_REQUEST['input'])) parse_str($_REQUEST['input'], $input);
	if (isset($input['ses-postid']) && is_numeric($input['ses-postid'])) $post_ID = sanitize_text_field($input['ses-postid']);
	$the_post = get_post($post_ID);
	$content = $the_post->post_content;
	$pattern = get_shortcode_regex();
	preg_match('/'. $pattern .'/s', $content, $matches);
	if (is_array($matches) && isset($matches[0])) $atts = shortcode_parse_atts(str_replace('[ses_pro', '', str_replace(']', '', $matches[0])));
}

Here we check if WordPress is DOING_AJAX before using shortcode_parse_atts() to get an array of all shortcode attributes and their associated values. This is another snippet from my plugin, SES Pro (Simple Email Signups).

References

Learn more

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