get_shortcode_regex()
Retrieve the shortcode regular expression for searching.
The regular expression combines the shortcode tags in the regular expression in a regex class.
The regular expression contains 6 different sub matches to help with parsing.
1 - An extra [ to allow for escaping shortcodes with double [[]]
2 - The shortcode name
3 - The shortcode argument list
4 - The self closing /
5 - The content of a shortcode when it wraps some content.
6 - An extra ] to allow for escaping shortcodes with double [[]]
No Hooks.
Return
String
. The shortcode search regular expression
Usage
get_shortcode_regex( $tagnames );
- $tagnames(array)
- List of shortcodes to find.
Default: 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. |