Codex

Function Reference/get shortcode regex

Contents

Description

Returns regular expression used to search for shortcodes inside posts.

This function combines all registered shortcode tags into a single regular expression.

Usage

<?php
	function your_prefix_detect_shortcode()
	{
		global $post;
		$pattern = get_shortcode_regex();
		preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches );
		
		if( is_array( $matches ) && array_key_exists( 2, $matches ) && in_array( 'your-shortcode', $matches[2] ) )
		{
			// shortcode is being used
		}
	}
	add_action( 'wp', 'your_prefix_detect_shortcode' );
?>

This can only be used when $post is available, of course. 'wp' is the earliest action you can hook into to get access to it.

Note: The example that previously appeared on this page used preg_match() instead of preg_match_all(), so it only detected the first shortcode used on the page. You should update any code that uses that example with the current example in order to fix that bug.

Parameters

None

Return Values

(string) 
The shortcode search regular expression.

Change Log

Since: 2.5

Source File

get_shortcode_regex() is located in wp-includes/shortcodes.php.

Related

Shortcode: do_shortcode(), add_shortcode(), remove_shortcode(), remove_all_shortcodes(), shortcode_atts(), strip_shortcodes()

See also index of Function Reference and index of Template Tags.