get_shortcode_regex()
Returns a regular expression that is used to find shortcodes in the text.
This function combines all registered shortcode tags into a single regular expression.
No Hooks.
Returns
String. Regular expression.
Usage
$pattern = get_shortcode_regex( $tagnames );
- $tagnames(array) (WP 4.4)
- List of shortcodes to find.
Default: null (all registered shortcodes)
Examples
#1 What the function returns
echo get_shortcode_regex(); // outputs about this line, depending on the registered shortcodes // \[(\[?)(embed|wp_caption|caption|gallery|playlist|audio|video)(?![\w-])([^\]\/]*(?:\/(?!\])[^\]\/]*)*?)(?:(\/)\]|\](?:([^\[]*+(?:\[(?!\/\])[^\[]*+)*+)\[\/\])?)(\]?)
If use the $tagnames parameter:
echo get_shortcode_regex( array('mytag') );
//> \[(\[?)(mytag)(?![\w-])([^\]\/]*(?:\/(?!\])[^\]\/]*)*?)(?:(\/)\]|\](?:([^\[]*+(?:\[(?!\/\])[^\[]*+)*+)\[\/\])?)(\]?) #2 Check if the specific shortcode is used in the post
Let's check if the your-shortcode is present in the text and do something if it is (for example enqueue css styles or js file):
add_action( 'wp', 'your_prefix_detect_shortcode' );
function your_prefix_detect_shortcode(){
global $post;
$pattern = get_shortcode_regex();
if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches )
&& array_key_exists( 2, $matches )
&& in_array( 'your-shortcode', $matches[2] )
) {
// enqueue css and js
}
}
This example will work if the global $post variable is defined. wp is the earliest action when we can use it.
See also a special function has_shortcode().
#3 Checking for shortcodes in multiple posts
This example is very similar to the previous one, the only difference being that it allows you to check all posts of current request (for example on category page) for the presence of the videoannotation shortcode we need in their content:
add_action( 'wp', 'your_prefix_detect_shortcode' );
function your_prefix_detect_shortcode(){
global $wp_query;
$posts = $wp_query->posts;
$pattern = get_shortcode_regex();
foreach ( $posts as $post ){
if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches )
&& array_key_exists( 2, $matches )
&& in_array( 'videoannotation', $matches[2] )
) {
// enqueue css and js
break; // we have determined that it is necessary to connect the styles and well...
}
}
}
Notes
- Global. Array.
$shortcode_tags
Changelog
| Since 2.5.0 | Introduced. |
| Since 4.4.0 | Added the $tagnames parameter. |