3 * WordPress API for creating bbcode like tags or what WordPress calls
4 * "shortcodes." The tag and attribute parsing or regular expression code is
5 * based on the Textpattern tag parser.
7 * A few examples are below:
10 * [shortcode foo="bar" baz="bing" /]
11 * [shortcode foo="bar"]content[/shortcode]
13 * Shortcode tags support attributes and enclosed content, but does not entirely
14 * support inline shortcodes in other shortcodes. You will have to call the
15 * shortcode parser in your function to account for that.
18 * Please be aware that the above note was made during the beta of WordPress 2.6
19 * and in the future may not be accurate. Please update the note when it is no
22 * To apply shortcode tags to content:
24 * $out = do_shortcode( $content );
26 * @link https://codex.wordpress.org/Shortcode_API
29 * @subpackage Shortcodes
34 * Container for storing shortcode tags and their hook to call for the shortcode
38 * @name $shortcode_tags
40 * @global array $shortcode_tags
42 $shortcode_tags = array();
45 * Add hook for shortcode tag.
47 * There can only be one hook for each shortcode. Which means that if another
48 * plugin has a similar shortcode, it will override yours or yours will override
49 * theirs depending on which order the plugins are included and/or ran.
51 * Simplest example of a shortcode tag using the API:
53 * // [footag foo="bar"]
54 * function footag_func( $atts ) {
59 * add_shortcode( 'footag', 'footag_func' );
61 * Example with nice attribute defaults:
63 * // [bartag foo="bar"]
64 * function bartag_func( $atts ) {
65 * $args = shortcode_atts( array(
67 * 'baz' => 'default baz',
70 * return "foo = {$args['foo']}";
72 * add_shortcode( 'bartag', 'bartag_func' );
74 * Example with enclosed content:
76 * // [baztag]content[/baztag]
77 * function baztag_func( $atts, $content = '' ) {
78 * return "content = $content";
80 * add_shortcode( 'baztag', 'baztag_func' );
84 * @global array $shortcode_tags
86 * @param string $tag Shortcode tag to be searched in post content.
87 * @param callable $func Hook to run when shortcode is found.
89 function add_shortcode($tag, $func) {
90 global $shortcode_tags;
92 if ( '' == trim( $tag ) ) {
93 $message = __( 'Invalid shortcode name: Empty name given.' );
94 _doing_it_wrong( __FUNCTION__, $message, '4.4.0' );
98 if ( 0 !== preg_match( '@[<>&/\[\]\x00-\x20]@', $tag ) ) {
99 /* translators: %s: shortcode name */
100 $message = sprintf( __( 'Invalid shortcode name: %s. Do not use spaces or reserved characters: & / < > [ ]' ), $tag );
101 _doing_it_wrong( __FUNCTION__, $message, '4.4.0' );
105 $shortcode_tags[ $tag ] = $func;
109 * Removes hook for shortcode.
113 * @global array $shortcode_tags
115 * @param string $tag Shortcode tag to remove hook for.
117 function remove_shortcode($tag) {
118 global $shortcode_tags;
120 unset($shortcode_tags[$tag]);
124 * Clear all shortcodes.
126 * This function is simple, it clears all of the shortcode tags by replacing the
127 * shortcodes global by a empty array. This is actually a very efficient method
128 * for removing all shortcodes.
132 * @global array $shortcode_tags
134 function remove_all_shortcodes() {
135 global $shortcode_tags;
137 $shortcode_tags = array();
141 * Whether a registered shortcode exists named $tag
145 * @global array $shortcode_tags List of shortcode tags and their callback hooks.
147 * @param string $tag Shortcode tag to check.
148 * @return bool Whether the given shortcode exists.
150 function shortcode_exists( $tag ) {
151 global $shortcode_tags;
152 return array_key_exists( $tag, $shortcode_tags );
156 * Whether the passed content contains the specified shortcode
160 * @global array $shortcode_tags
162 * @param string $content Content to search for shortcodes.
163 * @param string $tag Shortcode tag to check.
164 * @return bool Whether the passed content contains the given shortcode.
166 function has_shortcode( $content, $tag ) {
167 if ( false === strpos( $content, '[' ) ) {
171 if ( shortcode_exists( $tag ) ) {
172 preg_match_all( '/' . get_shortcode_regex() . '/', $content, $matches, PREG_SET_ORDER );
173 if ( empty( $matches ) )
176 foreach ( $matches as $shortcode ) {
177 if ( $tag === $shortcode[2] ) {
179 } elseif ( ! empty( $shortcode[5] ) && has_shortcode( $shortcode[5], $tag ) ) {
188 * Search content for shortcodes and filter shortcodes through their hooks.
190 * If there are no shortcode tags defined, then the content will be returned
191 * without any filtering. This might cause issues when plugins are disabled but
192 * the shortcode will still show up in the post or content.
196 * @global array $shortcode_tags List of shortcode tags and their callback hooks.
198 * @param string $content Content to search for shortcodes.
199 * @param bool $ignore_html When true, shortcodes inside HTML elements will be skipped.
200 * @return string Content with shortcodes filtered out.
202 function do_shortcode( $content, $ignore_html = false ) {
203 global $shortcode_tags;
205 if ( false === strpos( $content, '[' ) ) {
209 if (empty($shortcode_tags) || !is_array($shortcode_tags))
212 // Find all registered tag names in $content.
213 preg_match_all( '@\[([^<>&/\[\]\x00-\x20]++)@', $content, $matches );
214 $tagnames = array_intersect( array_keys( $shortcode_tags ), $matches[1] );
216 if ( empty( $tagnames ) ) {
220 $content = do_shortcodes_in_html_tags( $content, $ignore_html, $tagnames );
222 $pattern = get_shortcode_regex( $tagnames );
223 $content = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $content );
225 // Always restore square braces so we don't break things like <!--[if IE ]>
226 $content = unescape_invalid_shortcodes( $content );
232 * Retrieve the shortcode regular expression for searching.
234 * The regular expression combines the shortcode tags in the regular expression
237 * The regular expression contains 6 different sub matches to help with parsing.
239 * 1 - An extra [ to allow for escaping shortcodes with double [[]]
240 * 2 - The shortcode name
241 * 3 - The shortcode argument list
242 * 4 - The self closing /
243 * 5 - The content of a shortcode when it wraps some content.
244 * 6 - An extra ] to allow for escaping shortcodes with double [[]]
248 * @global array $shortcode_tags
250 * @param array $tagnames List of shortcodes to find. Optional. Defaults to all registered shortcodes.
251 * @return string The shortcode search regular expression
253 function get_shortcode_regex( $tagnames = null ) {
254 global $shortcode_tags;
256 if ( empty( $tagnames ) ) {
257 $tagnames = array_keys( $shortcode_tags );
259 $tagregexp = join( '|', array_map('preg_quote', $tagnames) );
261 // WARNING! Do not change this regex without changing do_shortcode_tag() and strip_shortcode_tag()
262 // Also, see shortcode_unautop() and shortcode.js.
264 '\\[' // Opening bracket
265 . '(\\[?)' // 1: Optional second opening bracket for escaping shortcodes: [[tag]]
266 . "($tagregexp)" // 2: Shortcode name
267 . '(?![\\w-])' // Not followed by word character or hyphen
268 . '(' // 3: Unroll the loop: Inside the opening shortcode tag
269 . '[^\\]\\/]*' // Not a closing bracket or forward slash
271 . '\\/(?!\\])' // A forward slash not followed by a closing bracket
272 . '[^\\]\\/]*' // Not a closing bracket or forward slash
276 . '(\\/)' // 4: Self closing tag ...
277 . '\\]' // ... and closing bracket
279 . '\\]' // Closing bracket
281 . '(' // 5: Unroll the loop: Optionally, anything between the opening and closing shortcode tags
282 . '[^\\[]*+' // Not an opening bracket
284 . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
285 . '[^\\[]*+' // Not an opening bracket
288 . '\\[\\/\\2\\]' // Closing shortcode tag
291 . '(\\]?)'; // 6: Optional second closing brocket for escaping shortcodes: [[tag]]
295 * Regular Expression callable for do_shortcode() for calling shortcode hook.
296 * @see get_shortcode_regex for details of the match array contents.
301 * @global array $shortcode_tags
303 * @param array $m Regular expression match array
304 * @return string|false False on failure.
306 function do_shortcode_tag( $m ) {
307 global $shortcode_tags;
309 // allow [[foo]] syntax for escaping a tag
310 if ( $m[1] == '[' && $m[6] == ']' ) {
311 return substr($m[0], 1, -1);
315 $attr = shortcode_parse_atts( $m[3] );
317 if ( ! is_callable( $shortcode_tags[ $tag ] ) ) {
318 /* translators: %s: shortcode tag */
319 $message = sprintf( __( 'Attempting to parse a shortcode without a valid callback: %s' ), $tag );
320 _doing_it_wrong( __FUNCTION__, $message, '4.3.0' );
324 if ( isset( $m[5] ) ) {
325 // enclosing tag - extra parameter
326 return $m[1] . call_user_func( $shortcode_tags[$tag], $attr, $m[5], $tag ) . $m[6];
329 return $m[1] . call_user_func( $shortcode_tags[$tag], $attr, null, $tag ) . $m[6];
334 * Search only inside HTML elements for shortcodes and process them.
336 * Any [ or ] characters remaining inside elements will be HTML encoded
337 * to prevent interference with shortcodes that are outside the elements.
338 * Assumes $content processed by KSES already. Users with unfiltered_html
339 * capability may get unexpected output if angle braces are nested in tags.
343 * @param string $content Content to search for shortcodes
344 * @param bool $ignore_html When true, all square braces inside elements will be encoded.
345 * @param array $tagnames List of shortcodes to find.
346 * @return string Content with shortcodes filtered out.
348 function do_shortcodes_in_html_tags( $content, $ignore_html, $tagnames ) {
349 // Normalize entities in unfiltered HTML before adding placeholders.
350 $trans = array( '[' => '[', ']' => ']' );
351 $content = strtr( $content, $trans );
352 $trans = array( '[' => '[', ']' => ']' );
354 $pattern = get_shortcode_regex( $tagnames );
355 $textarr = wp_html_split( $content );
357 foreach ( $textarr as &$element ) {
358 if ( '' == $element || '<' !== $element[0] ) {
362 $noopen = false === strpos( $element, '[' );
363 $noclose = false === strpos( $element, ']' );
364 if ( $noopen || $noclose ) {
365 // This element does not contain shortcodes.
366 if ( $noopen xor $noclose ) {
367 // Need to encode stray [ or ] chars.
368 $element = strtr( $element, $trans );
373 if ( $ignore_html || '<!--' === substr( $element, 0, 4 ) || '<![CDATA[' === substr( $element, 0, 9 ) ) {
374 // Encode all [ and ] chars.
375 $element = strtr( $element, $trans );
379 $attributes = wp_kses_attr_parse( $element );
380 if ( false === $attributes ) {
381 // Some plugins are doing things like [name] <[email]>.
382 if ( 1 === preg_match( '%^<\s*\[\[?[^\[\]]+\]%', $element ) ) {
383 $element = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $element );
386 // Looks like we found some crazy unfiltered HTML. Skipping it for sanity.
387 $element = strtr( $element, $trans );
392 $front = array_shift( $attributes );
393 $back = array_pop( $attributes );
395 preg_match('%[a-zA-Z0-9]+%', $front, $matches);
396 $elname = $matches[0];
398 // Look for shortcodes in each attribute separately.
399 foreach ( $attributes as &$attr ) {
400 $open = strpos( $attr, '[' );
401 $close = strpos( $attr, ']' );
402 if ( false === $open || false === $close ) {
403 continue; // Go to next attribute. Square braces will be escaped at end of loop.
405 $double = strpos( $attr, '"' );
406 $single = strpos( $attr, "'" );
407 if ( ( false === $single || $open < $single ) && ( false === $double || $open < $double ) ) {
408 // $attr like '[shortcode]' or 'name = [shortcode]' implies unfiltered_html.
409 // In this specific situation we assume KSES did not run because the input
410 // was written by an administrator, so we should avoid changing the output
411 // and we do not need to run KSES here.
412 $attr = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $attr );
414 // $attr like 'name = "[shortcode]"' or "name = '[shortcode]'"
415 // We do not know if $content was unfiltered. Assume KSES ran before shortcodes.
417 $new_attr = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $attr, -1, $count );
419 // Sanitize the shortcode output using KSES.
420 $new_attr = wp_kses_one_attr( $new_attr, $elname );
421 if ( '' !== trim( $new_attr ) ) {
422 // The shortcode is safe to use now.
428 $element = $front . implode( '', $attributes ) . $back;
430 // Now encode any remaining [ or ] chars.
431 $element = strtr( $element, $trans );
434 $content = implode( '', $textarr );
440 * Remove placeholders added by do_shortcodes_in_html_tags().
444 * @param string $content Content to search for placeholders.
445 * @return string Content with placeholders removed.
447 function unescape_invalid_shortcodes( $content ) {
448 // Clean up entire string, avoids re-parsing HTML.
449 $trans = array( '[' => '[', ']' => ']' );
450 $content = strtr( $content, $trans );
456 * Retrieve the shortcode attributes regex.
460 * @return string The shortcode attribute regular expression
462 function get_shortcode_atts_regex() {
463 return '/([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*\'([^\']*)\'(?:\s|$)|([\w-]+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/';
467 * Retrieve all attributes from the shortcodes tag.
469 * The attributes list has the attribute name as the key and the value of the
470 * attribute as the value in the key/value pair. This allows for easier
471 * retrieval of the attributes, since all attributes have to be known.
475 * @param string $text
476 * @return array|string List of attribute values.
477 * Returns empty array if trim( $text ) == '""'.
478 * Returns empty string if trim( $text ) == ''.
479 * All other matches are checked for not empty().
481 function shortcode_parse_atts($text) {
483 $pattern = get_shortcode_atts_regex();
484 $text = preg_replace("/[\x{00a0}\x{200b}]+/u", " ", $text);
485 if ( preg_match_all($pattern, $text, $match, PREG_SET_ORDER) ) {
486 foreach ($match as $m) {
488 $atts[strtolower($m[1])] = stripcslashes($m[2]);
489 elseif (!empty($m[3]))
490 $atts[strtolower($m[3])] = stripcslashes($m[4]);
491 elseif (!empty($m[5]))
492 $atts[strtolower($m[5])] = stripcslashes($m[6]);
493 elseif (isset($m[7]) && strlen($m[7]))
494 $atts[] = stripcslashes($m[7]);
495 elseif (isset($m[8]))
496 $atts[] = stripcslashes($m[8]);
499 // Reject any unclosed HTML elements
500 foreach( $atts as &$value ) {
501 if ( false !== strpos( $value, '<' ) ) {
502 if ( 1 !== preg_match( '/^[^<]*+(?:<[^>]*+>[^<]*+)*+$/', $value ) ) {
508 $atts = ltrim($text);
514 * Combine user attributes with known attributes and fill in defaults when needed.
516 * The pairs should be considered to be all of the attributes which are
517 * supported by the caller and given as a list. The returned attributes will
518 * only contain the attributes in the $pairs list.
520 * If the $atts list has unsupported attributes, then they will be ignored and
521 * removed from the final returned list.
525 * @param array $pairs Entire list of supported attributes and their defaults.
526 * @param array $atts User defined attributes in shortcode tag.
527 * @param string $shortcode Optional. The name of the shortcode, provided for context to enable filtering
528 * @return array Combined and filtered attribute list.
530 function shortcode_atts( $pairs, $atts, $shortcode = '' ) {
531 $atts = (array)$atts;
533 foreach ($pairs as $name => $default) {
534 if ( array_key_exists($name, $atts) )
535 $out[$name] = $atts[$name];
537 $out[$name] = $default;
540 * Filter a shortcode's default attributes.
542 * If the third parameter of the shortcode_atts() function is present then this filter is available.
543 * The third parameter, $shortcode, is the name of the shortcode.
546 * @since 4.4.0 Added the `$shortcode` parameter.
548 * @param array $out The output array of shortcode attributes.
549 * @param array $pairs The supported attributes and their defaults.
550 * @param array $atts The user defined shortcode attributes.
551 * @param string $shortcode The shortcode name.
554 $out = apply_filters( "shortcode_atts_{$shortcode}", $out, $pairs, $atts, $shortcode );
561 * Remove all shortcode tags from the given content.
565 * @global array $shortcode_tags
567 * @param string $content Content to remove shortcode tags.
568 * @return string Content without shortcode tags.
570 function strip_shortcodes( $content ) {
571 global $shortcode_tags;
573 if ( false === strpos( $content, '[' ) ) {
577 if (empty($shortcode_tags) || !is_array($shortcode_tags))
580 // Find all registered tag names in $content.
581 preg_match_all( '@\[([^<>&/\[\]\x00-\x20]++)@', $content, $matches );
582 $tagnames = array_intersect( array_keys( $shortcode_tags ), $matches[1] );
584 if ( empty( $tagnames ) ) {
588 $content = do_shortcodes_in_html_tags( $content, true, $tagnames );
590 $pattern = get_shortcode_regex( $tagnames );
591 $content = preg_replace_callback( "/$pattern/", 'strip_shortcode_tag', $content );
593 // Always restore square braces so we don't break things like <!--[if IE ]>
594 $content = unescape_invalid_shortcodes( $content );
602 * @return string|false
604 function strip_shortcode_tag( $m ) {
605 // allow [[foo]] syntax for escaping a tag
606 if ( $m[1] == '[' && $m[6] == ']' ) {
607 return substr($m[0], 1, -1);
610 return $m[1] . $m[6];