[ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 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. 6 * 7 * A few examples are below: 8 * 9 * [shortcode /] 10 * [shortcode foo="bar" baz="bing" /] 11 * [shortcode foo="bar"]content[/shortcode] 12 * 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. 16 * 17 * {@internal 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 20 * longer the case.}} 21 * 22 * To apply shortcode tags to content: 23 * 24 * $out = do_shortcode( $content ); 25 * 26 * @link https://developer.wordpress.org/plugins/shortcodes/ 27 * 28 * @package WordPress 29 * @subpackage Shortcodes 30 * @since 2.5.0 31 */ 32 33 /** 34 * Container for storing shortcode tags and their hook to call for the shortcode 35 * 36 * @since 2.5.0 37 * 38 * @name $shortcode_tags 39 * @var array 40 * @global array $shortcode_tags 41 */ 42 $shortcode_tags = array(); 43 44 /** 45 * Adds a new shortcode. 46 * 47 * Care should be taken through prefixing or other means to ensure that the 48 * shortcode tag being added is unique and will not conflict with other, 49 * already-added shortcode tags. In the event of a duplicated tag, the tag 50 * loaded last will take precedence. 51 * 52 * @since 2.5.0 53 * 54 * @global array $shortcode_tags 55 * 56 * @param string $tag Shortcode tag to be searched in post content. 57 * @param callable $callback The callback function to run when the shortcode is found. 58 * Every shortcode callback is passed three parameters by default, 59 * including an array of attributes (`$atts`), the shortcode content 60 * or null if not set (`$content`), and finally the shortcode tag 61 * itself (`$shortcode_tag`), in that order. 62 */ 63 function add_shortcode( $tag, $callback ) { 64 global $shortcode_tags; 65 66 if ( '' == trim( $tag ) ) { 67 $message = __( 'Invalid shortcode name: Empty name given.' ); 68 _doing_it_wrong( __FUNCTION__, $message, '4.4.0' ); 69 return; 70 } 71 72 if ( 0 !== preg_match( '@[<>&/\[\]\x00-\x20=]@', $tag ) ) { 73 /* translators: 1: Shortcode name, 2: Space-separated list of reserved characters. */ 74 $message = sprintf( __( 'Invalid shortcode name: %1$s. Do not use spaces or reserved characters: %2$s' ), $tag, '& / < > [ ] =' ); 75 _doing_it_wrong( __FUNCTION__, $message, '4.4.0' ); 76 return; 77 } 78 79 $shortcode_tags[ $tag ] = $callback; 80 } 81 82 /** 83 * Removes hook for shortcode. 84 * 85 * @since 2.5.0 86 * 87 * @global array $shortcode_tags 88 * 89 * @param string $tag Shortcode tag to remove hook for. 90 */ 91 function remove_shortcode( $tag ) { 92 global $shortcode_tags; 93 94 unset( $shortcode_tags[ $tag ] ); 95 } 96 97 /** 98 * Clear all shortcodes. 99 * 100 * This function is simple, it clears all of the shortcode tags by replacing the 101 * shortcodes global by a empty array. This is actually a very efficient method 102 * for removing all shortcodes. 103 * 104 * @since 2.5.0 105 * 106 * @global array $shortcode_tags 107 */ 108 function remove_all_shortcodes() { 109 global $shortcode_tags; 110 111 $shortcode_tags = array(); 112 } 113 114 /** 115 * Whether a registered shortcode exists named $tag 116 * 117 * @since 3.6.0 118 * 119 * @global array $shortcode_tags List of shortcode tags and their callback hooks. 120 * 121 * @param string $tag Shortcode tag to check. 122 * @return bool Whether the given shortcode exists. 123 */ 124 function shortcode_exists( $tag ) { 125 global $shortcode_tags; 126 return array_key_exists( $tag, $shortcode_tags ); 127 } 128 129 /** 130 * Whether the passed content contains the specified shortcode 131 * 132 * @since 3.6.0 133 * 134 * @global array $shortcode_tags 135 * 136 * @param string $content Content to search for shortcodes. 137 * @param string $tag Shortcode tag to check. 138 * @return bool Whether the passed content contains the given shortcode. 139 */ 140 function has_shortcode( $content, $tag ) { 141 if ( false === strpos( $content, '[' ) ) { 142 return false; 143 } 144 145 if ( shortcode_exists( $tag ) ) { 146 preg_match_all( '/' . get_shortcode_regex() . '/', $content, $matches, PREG_SET_ORDER ); 147 if ( empty( $matches ) ) { 148 return false; 149 } 150 151 foreach ( $matches as $shortcode ) { 152 if ( $tag === $shortcode[2] ) { 153 return true; 154 } elseif ( ! empty( $shortcode[5] ) && has_shortcode( $shortcode[5], $tag ) ) { 155 return true; 156 } 157 } 158 } 159 return false; 160 } 161 162 /** 163 * Search content for shortcodes and filter shortcodes through their hooks. 164 * 165 * If there are no shortcode tags defined, then the content will be returned 166 * without any filtering. This might cause issues when plugins are disabled but 167 * the shortcode will still show up in the post or content. 168 * 169 * @since 2.5.0 170 * 171 * @global array $shortcode_tags List of shortcode tags and their callback hooks. 172 * 173 * @param string $content Content to search for shortcodes. 174 * @param bool $ignore_html When true, shortcodes inside HTML elements will be skipped. 175 * @return string Content with shortcodes filtered out. 176 */ 177 function do_shortcode( $content, $ignore_html = false ) { 178 global $shortcode_tags; 179 180 if ( false === strpos( $content, '[' ) ) { 181 return $content; 182 } 183 184 if ( empty( $shortcode_tags ) || ! is_array( $shortcode_tags ) ) { 185 return $content; 186 } 187 188 // Find all registered tag names in $content. 189 preg_match_all( '@\[([^<>&/\[\]\x00-\x20=]++)@', $content, $matches ); 190 $tagnames = array_intersect( array_keys( $shortcode_tags ), $matches[1] ); 191 192 if ( empty( $tagnames ) ) { 193 return $content; 194 } 195 196 $content = do_shortcodes_in_html_tags( $content, $ignore_html, $tagnames ); 197 198 $pattern = get_shortcode_regex( $tagnames ); 199 $content = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $content ); 200 201 // Always restore square braces so we don't break things like <!--[if IE ]> 202 $content = unescape_invalid_shortcodes( $content ); 203 204 return $content; 205 } 206 207 /** 208 * Retrieve the shortcode regular expression for searching. 209 * 210 * The regular expression combines the shortcode tags in the regular expression 211 * in a regex class. 212 * 213 * The regular expression contains 6 different sub matches to help with parsing. 214 * 215 * 1 - An extra [ to allow for escaping shortcodes with double [[]] 216 * 2 - The shortcode name 217 * 3 - The shortcode argument list 218 * 4 - The self closing / 219 * 5 - The content of a shortcode when it wraps some content. 220 * 6 - An extra ] to allow for escaping shortcodes with double [[]] 221 * 222 * @since 2.5.0 223 * @since 4.4.0 Added the `$tagnames` parameter. 224 * 225 * @global array $shortcode_tags 226 * 227 * @param array $tagnames Optional. List of shortcodes to find. Defaults to all registered shortcodes. 228 * @return string The shortcode search regular expression 229 */ 230 function get_shortcode_regex( $tagnames = null ) { 231 global $shortcode_tags; 232 233 if ( empty( $tagnames ) ) { 234 $tagnames = array_keys( $shortcode_tags ); 235 } 236 $tagregexp = join( '|', array_map( 'preg_quote', $tagnames ) ); 237 238 // WARNING! Do not change this regex without changing do_shortcode_tag() and strip_shortcode_tag() 239 // Also, see shortcode_unautop() and shortcode.js. 240 241 // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation 242 return 243 '\\[' // Opening bracket 244 . '(\\[?)' // 1: Optional second opening bracket for escaping shortcodes: [[tag]] 245 . "($tagregexp)" // 2: Shortcode name 246 . '(?![\\w-])' // Not followed by word character or hyphen 247 . '(' // 3: Unroll the loop: Inside the opening shortcode tag 248 . '[^\\]\\/]*' // Not a closing bracket or forward slash 249 . '(?:' 250 . '\\/(?!\\])' // A forward slash not followed by a closing bracket 251 . '[^\\]\\/]*' // Not a closing bracket or forward slash 252 . ')*?' 253 . ')' 254 . '(?:' 255 . '(\\/)' // 4: Self closing tag ... 256 . '\\]' // ... and closing bracket 257 . '|' 258 . '\\]' // Closing bracket 259 . '(?:' 260 . '(' // 5: Unroll the loop: Optionally, anything between the opening and closing shortcode tags 261 . '[^\\[]*+' // Not an opening bracket 262 . '(?:' 263 . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag 264 . '[^\\[]*+' // Not an opening bracket 265 . ')*+' 266 . ')' 267 . '\\[\\/\\2\\]' // Closing shortcode tag 268 . ')?' 269 . ')' 270 . '(\\]?)'; // 6: Optional second closing brocket for escaping shortcodes: [[tag]] 271 // phpcs:enable 272 } 273 274 /** 275 * Regular Expression callable for do_shortcode() for calling shortcode hook. 276 * 277 * @see get_shortcode_regex for details of the match array contents. 278 * 279 * @since 2.5.0 280 * @access private 281 * 282 * @global array $shortcode_tags 283 * 284 * @param array $m Regular expression match array 285 * @return string|false False on failure. 286 */ 287 function do_shortcode_tag( $m ) { 288 global $shortcode_tags; 289 290 // allow [[foo]] syntax for escaping a tag 291 if ( $m[1] == '[' && $m[6] == ']' ) { 292 return substr( $m[0], 1, -1 ); 293 } 294 295 $tag = $m[2]; 296 $attr = shortcode_parse_atts( $m[3] ); 297 298 if ( ! is_callable( $shortcode_tags[ $tag ] ) ) { 299 /* translators: %s: Shortcode tag. */ 300 $message = sprintf( __( 'Attempting to parse a shortcode without a valid callback: %s' ), $tag ); 301 _doing_it_wrong( __FUNCTION__, $message, '4.3.0' ); 302 return $m[0]; 303 } 304 305 /** 306 * Filters whether to call a shortcode callback. 307 * 308 * Returning a non-false value from filter will short-circuit the 309 * shortcode generation process, returning that value instead. 310 * 311 * @since 4.7.0 312 * 313 * @param false|string $return Short-circuit return value. Either false or the value to replace the shortcode with. 314 * @param string $tag Shortcode name. 315 * @param array|string $attr Shortcode attributes array or empty string. 316 * @param array $m Regular expression match array. 317 */ 318 $return = apply_filters( 'pre_do_shortcode_tag', false, $tag, $attr, $m ); 319 if ( false !== $return ) { 320 return $return; 321 } 322 323 $content = isset( $m[5] ) ? $m[5] : null; 324 325 $output = $m[1] . call_user_func( $shortcode_tags[ $tag ], $attr, $content, $tag ) . $m[6]; 326 327 /** 328 * Filters the output created by a shortcode callback. 329 * 330 * @since 4.7.0 331 * 332 * @param string $output Shortcode output. 333 * @param string $tag Shortcode name. 334 * @param array|string $attr Shortcode attributes array or empty string. 335 * @param array $m Regular expression match array. 336 */ 337 return apply_filters( 'do_shortcode_tag', $output, $tag, $attr, $m ); 338 } 339 340 /** 341 * Search only inside HTML elements for shortcodes and process them. 342 * 343 * Any [ or ] characters remaining inside elements will be HTML encoded 344 * to prevent interference with shortcodes that are outside the elements. 345 * Assumes $content processed by KSES already. Users with unfiltered_html 346 * capability may get unexpected output if angle braces are nested in tags. 347 * 348 * @since 4.2.3 349 * 350 * @param string $content Content to search for shortcodes 351 * @param bool $ignore_html When true, all square braces inside elements will be encoded. 352 * @param array $tagnames List of shortcodes to find. 353 * @return string Content with shortcodes filtered out. 354 */ 355 function do_shortcodes_in_html_tags( $content, $ignore_html, $tagnames ) { 356 // Normalize entities in unfiltered HTML before adding placeholders. 357 $trans = array( 358 '[' => '[', 359 ']' => ']', 360 ); 361 $content = strtr( $content, $trans ); 362 $trans = array( 363 '[' => '[', 364 ']' => ']', 365 ); 366 367 $pattern = get_shortcode_regex( $tagnames ); 368 $textarr = wp_html_split( $content ); 369 370 foreach ( $textarr as &$element ) { 371 if ( '' == $element || '<' !== $element[0] ) { 372 continue; 373 } 374 375 $noopen = false === strpos( $element, '[' ); 376 $noclose = false === strpos( $element, ']' ); 377 if ( $noopen || $noclose ) { 378 // This element does not contain shortcodes. 379 if ( $noopen xor $noclose ) { 380 // Need to encode stray [ or ] chars. 381 $element = strtr( $element, $trans ); 382 } 383 continue; 384 } 385 386 if ( $ignore_html || '<!--' === substr( $element, 0, 4 ) || '<![CDATA[' === substr( $element, 0, 9 ) ) { 387 // Encode all [ and ] chars. 388 $element = strtr( $element, $trans ); 389 continue; 390 } 391 392 $attributes = wp_kses_attr_parse( $element ); 393 if ( false === $attributes ) { 394 // Some plugins are doing things like [name] <[email]>. 395 if ( 1 === preg_match( '%^<\s*\[\[?[^\[\]]+\]%', $element ) ) { 396 $element = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $element ); 397 } 398 399 // Looks like we found some crazy unfiltered HTML. Skipping it for sanity. 400 $element = strtr( $element, $trans ); 401 continue; 402 } 403 404 // Get element name 405 $front = array_shift( $attributes ); 406 $back = array_pop( $attributes ); 407 $matches = array(); 408 preg_match( '%[a-zA-Z0-9]+%', $front, $matches ); 409 $elname = $matches[0]; 410 411 // Look for shortcodes in each attribute separately. 412 foreach ( $attributes as &$attr ) { 413 $open = strpos( $attr, '[' ); 414 $close = strpos( $attr, ']' ); 415 if ( false === $open || false === $close ) { 416 continue; // Go to next attribute. Square braces will be escaped at end of loop. 417 } 418 $double = strpos( $attr, '"' ); 419 $single = strpos( $attr, "'" ); 420 if ( ( false === $single || $open < $single ) && ( false === $double || $open < $double ) ) { 421 // $attr like '[shortcode]' or 'name = [shortcode]' implies unfiltered_html. 422 // In this specific situation we assume KSES did not run because the input 423 // was written by an administrator, so we should avoid changing the output 424 // and we do not need to run KSES here. 425 $attr = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $attr ); 426 } else { 427 // $attr like 'name = "[shortcode]"' or "name = '[shortcode]'" 428 // We do not know if $content was unfiltered. Assume KSES ran before shortcodes. 429 $count = 0; 430 $new_attr = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $attr, -1, $count ); 431 if ( $count > 0 ) { 432 // Sanitize the shortcode output using KSES. 433 $new_attr = wp_kses_one_attr( $new_attr, $elname ); 434 if ( '' !== trim( $new_attr ) ) { 435 // The shortcode is safe to use now. 436 $attr = $new_attr; 437 } 438 } 439 } 440 } 441 $element = $front . implode( '', $attributes ) . $back; 442 443 // Now encode any remaining [ or ] chars. 444 $element = strtr( $element, $trans ); 445 } 446 447 $content = implode( '', $textarr ); 448 449 return $content; 450 } 451 452 /** 453 * Remove placeholders added by do_shortcodes_in_html_tags(). 454 * 455 * @since 4.2.3 456 * 457 * @param string $content Content to search for placeholders. 458 * @return string Content with placeholders removed. 459 */ 460 function unescape_invalid_shortcodes( $content ) { 461 // Clean up entire string, avoids re-parsing HTML. 462 $trans = array( 463 '[' => '[', 464 ']' => ']', 465 ); 466 467 $content = strtr( $content, $trans ); 468 469 return $content; 470 } 471 472 /** 473 * Retrieve the shortcode attributes regex. 474 * 475 * @since 4.4.0 476 * 477 * @return string The shortcode attribute regular expression 478 */ 479 function get_shortcode_atts_regex() { 480 return '/([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*\'([^\']*)\'(?:\s|$)|([\w-]+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|\'([^\']*)\'(?:\s|$)|(\S+)(?:\s|$)/'; 481 } 482 483 /** 484 * Retrieve all attributes from the shortcodes tag. 485 * 486 * The attributes list has the attribute name as the key and the value of the 487 * attribute as the value in the key/value pair. This allows for easier 488 * retrieval of the attributes, since all attributes have to be known. 489 * 490 * @since 2.5.0 491 * 492 * @param string $text 493 * @return array|string List of attribute values. 494 * Returns empty array if trim( $text ) == '""'. 495 * Returns empty string if trim( $text ) == ''. 496 * All other matches are checked for not empty(). 497 */ 498 function shortcode_parse_atts( $text ) { 499 $atts = array(); 500 $pattern = get_shortcode_atts_regex(); 501 $text = preg_replace( "/[\x{00a0}\x{200b}]+/u", ' ', $text ); 502 if ( preg_match_all( $pattern, $text, $match, PREG_SET_ORDER ) ) { 503 foreach ( $match as $m ) { 504 if ( ! empty( $m[1] ) ) { 505 $atts[ strtolower( $m[1] ) ] = stripcslashes( $m[2] ); 506 } elseif ( ! empty( $m[3] ) ) { 507 $atts[ strtolower( $m[3] ) ] = stripcslashes( $m[4] ); 508 } elseif ( ! empty( $m[5] ) ) { 509 $atts[ strtolower( $m[5] ) ] = stripcslashes( $m[6] ); 510 } elseif ( isset( $m[7] ) && strlen( $m[7] ) ) { 511 $atts[] = stripcslashes( $m[7] ); 512 } elseif ( isset( $m[8] ) && strlen( $m[8] ) ) { 513 $atts[] = stripcslashes( $m[8] ); 514 } elseif ( isset( $m[9] ) ) { 515 $atts[] = stripcslashes( $m[9] ); 516 } 517 } 518 519 // Reject any unclosed HTML elements. 520 foreach ( $atts as &$value ) { 521 if ( false !== strpos( $value, '<' ) ) { 522 if ( 1 !== preg_match( '/^[^<]*+(?:<[^>]*+>[^<]*+)*+$/', $value ) ) { 523 $value = ''; 524 } 525 } 526 } 527 } else { 528 $atts = ltrim( $text ); 529 } 530 531 return $atts; 532 } 533 534 /** 535 * Combine user attributes with known attributes and fill in defaults when needed. 536 * 537 * The pairs should be considered to be all of the attributes which are 538 * supported by the caller and given as a list. The returned attributes will 539 * only contain the attributes in the $pairs list. 540 * 541 * If the $atts list has unsupported attributes, then they will be ignored and 542 * removed from the final returned list. 543 * 544 * @since 2.5.0 545 * 546 * @param array $pairs Entire list of supported attributes and their defaults. 547 * @param array $atts User defined attributes in shortcode tag. 548 * @param string $shortcode Optional. The name of the shortcode, provided for context to enable filtering 549 * @return array Combined and filtered attribute list. 550 */ 551 function shortcode_atts( $pairs, $atts, $shortcode = '' ) { 552 $atts = (array) $atts; 553 $out = array(); 554 foreach ( $pairs as $name => $default ) { 555 if ( array_key_exists( $name, $atts ) ) { 556 $out[ $name ] = $atts[ $name ]; 557 } else { 558 $out[ $name ] = $default; 559 } 560 } 561 562 if ( $shortcode ) { 563 /** 564 * Filters a shortcode's default attributes. 565 * 566 * If the third parameter of the shortcode_atts() function is present then this filter is available. 567 * The third parameter, $shortcode, is the name of the shortcode. 568 * 569 * @since 3.6.0 570 * @since 4.4.0 Added the `$shortcode` parameter. 571 * 572 * @param array $out The output array of shortcode attributes. 573 * @param array $pairs The supported attributes and their defaults. 574 * @param array $atts The user defined shortcode attributes. 575 * @param string $shortcode The shortcode name. 576 */ 577 $out = apply_filters( "shortcode_atts_{$shortcode}", $out, $pairs, $atts, $shortcode ); 578 } 579 580 return $out; 581 } 582 583 /** 584 * Remove all shortcode tags from the given content. 585 * 586 * @since 2.5.0 587 * 588 * @global array $shortcode_tags 589 * 590 * @param string $content Content to remove shortcode tags. 591 * @return string Content without shortcode tags. 592 */ 593 function strip_shortcodes( $content ) { 594 global $shortcode_tags; 595 596 if ( false === strpos( $content, '[' ) ) { 597 return $content; 598 } 599 600 if ( empty( $shortcode_tags ) || ! is_array( $shortcode_tags ) ) { 601 return $content; 602 } 603 604 // Find all registered tag names in $content. 605 preg_match_all( '@\[([^<>&/\[\]\x00-\x20=]++)@', $content, $matches ); 606 607 $tags_to_remove = array_keys( $shortcode_tags ); 608 609 /** 610 * Filters the list of shortcode tags to remove from the content. 611 * 612 * @since 4.7.0 613 * 614 * @param array $tags_to_remove Array of shortcode tags to remove. 615 * @param string $content Content shortcodes are being removed from. 616 */ 617 $tags_to_remove = apply_filters( 'strip_shortcodes_tagnames', $tags_to_remove, $content ); 618 619 $tagnames = array_intersect( $tags_to_remove, $matches[1] ); 620 621 if ( empty( $tagnames ) ) { 622 return $content; 623 } 624 625 $content = do_shortcodes_in_html_tags( $content, true, $tagnames ); 626 627 $pattern = get_shortcode_regex( $tagnames ); 628 $content = preg_replace_callback( "/$pattern/", 'strip_shortcode_tag', $content ); 629 630 // Always restore square braces so we don't break things like <!--[if IE ]> 631 $content = unescape_invalid_shortcodes( $content ); 632 633 return $content; 634 } 635 636 /** 637 * Strips a shortcode tag based on RegEx matches against post content. 638 * 639 * @since 3.3.0 640 * 641 * @param array $m RegEx matches against post content. 642 * @return string|false The content stripped of the tag, otherwise false. 643 */ 644 function strip_shortcode_tag( $m ) { 645 // allow [[foo]] syntax for escaping a tag 646 if ( $m[1] == '[' && $m[6] == ']' ) { 647 return substr( $m[0], 1, -1 ); 648 } 649 650 return $m[1] . $m[6]; 651 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated: Sat Nov 23 20:47:33 2019 | Cross-referenced by PHPXref 0.7 |