[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> shortcodes.php (source)

   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   * @phpstan-param non-empty-string $tag
  64   */
  65  function add_shortcode( $tag, $callback ) {
  66      global $shortcode_tags;
  67  
  68      if ( '' === trim( $tag ) ) {
  69          _doing_it_wrong(
  70              __FUNCTION__,
  71              __( 'Invalid shortcode name: Empty name given.' ),
  72              '4.4.0'
  73          );
  74          return;
  75      }
  76  
  77      if ( 0 !== preg_match( '@[<>&/\[\]\x00-\x20=]@', $tag ) ) {
  78          _doing_it_wrong(
  79              __FUNCTION__,
  80              sprintf(
  81                  /* translators: 1: Shortcode name, 2: Space-separated list of reserved characters. */
  82                  __( 'Invalid shortcode name: %1$s. Do not use spaces or reserved characters: %2$s' ),
  83                  $tag,
  84                  '& / < > [ ] ='
  85              ),
  86              '4.4.0'
  87          );
  88          return;
  89      }
  90  
  91      $shortcode_tags[ $tag ] = $callback;
  92  }
  93  
  94  /**
  95   * Removes hook for shortcode.
  96   *
  97   * @since 2.5.0
  98   *
  99   * @global array $shortcode_tags
 100   *
 101   * @param string $tag Shortcode tag to remove hook for.
 102   */
 103  function remove_shortcode( $tag ) {
 104      global $shortcode_tags;
 105  
 106      unset( $shortcode_tags[ $tag ] );
 107  }
 108  
 109  /**
 110   * Clears all shortcodes.
 111   *
 112   * This function clears all of the shortcode tags by replacing the shortcodes global with
 113   * an empty array. This is actually an efficient method for removing all shortcodes.
 114   *
 115   * @since 2.5.0
 116   *
 117   * @global array $shortcode_tags
 118   */
 119  function remove_all_shortcodes() {
 120      global $shortcode_tags;
 121  
 122      $shortcode_tags = array();
 123  }
 124  
 125  /**
 126   * Determines whether a registered shortcode exists named $tag.
 127   *
 128   * @since 3.6.0
 129   *
 130   * @global array $shortcode_tags List of shortcode tags and their callback hooks.
 131   *
 132   * @param string $tag Shortcode tag to check.
 133   * @return bool Whether the given shortcode exists.
 134   *
 135   * @phpstan-assert-if-true =non-empty-string $tag
 136   */
 137  function shortcode_exists( $tag ) {
 138      global $shortcode_tags;
 139      return array_key_exists( $tag, $shortcode_tags );
 140  }
 141  
 142  /**
 143   * Determines whether the passed content contains the specified shortcode.
 144   *
 145   * @since 3.6.0
 146   *
 147   * @global array $shortcode_tags
 148   *
 149   * @param string $content Content to search for shortcodes.
 150   * @param string $tag     Shortcode tag to check.
 151   * @return bool Whether the passed content contains the given shortcode.
 152   *
 153   * @phpstan-assert-if-true =non-falsy-string $content
 154   * @phpstan-assert-if-true =non-empty-string $tag
 155   * @phpstan-return ( $tag is '' ? false : ( $content is empty ? false : bool ) )
 156   */
 157  function has_shortcode( $content, $tag ) {
 158      if ( ! str_contains( $content, '[' ) ) {
 159          return false;
 160      }
 161  
 162      if ( shortcode_exists( $tag ) ) {
 163          preg_match_all( '/' . get_shortcode_regex() . '/', $content, $matches, PREG_SET_ORDER );
 164          if ( empty( $matches ) ) {
 165              return false;
 166          }
 167  
 168          foreach ( $matches as $shortcode ) {
 169              if ( $tag === $shortcode[2] ) {
 170                  return true;
 171              } elseif ( ! empty( $shortcode[5] ) && has_shortcode( $shortcode[5], $tag ) ) {
 172                  return true;
 173              }
 174          }
 175      }
 176      return false;
 177  }
 178  
 179  /**
 180   * Returns a list of registered shortcode names found in the given content.
 181   *
 182   * Example usage:
 183   *
 184   *     get_shortcode_tags_in_content( '[audio src="file.mp3"][/audio] [foo] [gallery ids="1,2,3"]' );
 185   *     // array( 'audio', 'gallery' )
 186   *
 187   * @since 6.3.2
 188   *
 189   * @param string $content The content to check.
 190   * @return string[] An array of registered shortcode names found in the content.
 191   *
 192   * @phpstan-return list<string>
 193   */
 194  function get_shortcode_tags_in_content( $content ) {
 195      if ( ! str_contains( $content, '[' ) ) {
 196          return array();
 197      }
 198  
 199      preg_match_all( '/' . get_shortcode_regex() . '/', $content, $matches, PREG_SET_ORDER );
 200      if ( empty( $matches ) ) {
 201          return array();
 202      }
 203  
 204      $tags = array();
 205      foreach ( $matches as $shortcode ) {
 206          $tags[] = $shortcode[2];
 207  
 208          if ( ! empty( $shortcode[5] ) ) {
 209              $deep_tags = get_shortcode_tags_in_content( $shortcode[5] );
 210              if ( ! empty( $deep_tags ) ) {
 211                  $tags = array_merge( $tags, $deep_tags );
 212              }
 213          }
 214      }
 215  
 216      return $tags;
 217  }
 218  
 219  /**
 220   * Searches content for shortcodes and filter shortcodes through their hooks.
 221   *
 222   * This function is an alias for do_shortcode().
 223   *
 224   * @since 5.4.0
 225   *
 226   * @see do_shortcode()
 227   *
 228   * @param string $content     Content to search for shortcodes.
 229   * @param bool   $ignore_html When true, shortcodes inside HTML elements will be skipped.
 230   *                            Default false.
 231   * @return string Content with shortcodes filtered out.
 232   */
 233  function apply_shortcodes( $content, $ignore_html = false ) {
 234      return do_shortcode( $content, $ignore_html );
 235  }
 236  
 237  /**
 238   * Searches content for shortcodes and filter shortcodes through their hooks.
 239   *
 240   * If there are no shortcode tags defined, then the content will be returned
 241   * without any filtering. This might cause issues when plugins are disabled but
 242   * the shortcode will still show up in the post or content.
 243   *
 244   * @since 2.5.0
 245   *
 246   * @global array $shortcode_tags List of shortcode tags and their callback hooks.
 247   *
 248   * @param string $content     Content to search for shortcodes.
 249   * @param bool   $ignore_html When true, shortcodes inside HTML elements will be skipped.
 250   *                            Default false.
 251   * @return string Content with shortcodes filtered out.
 252   */
 253  function do_shortcode( $content, $ignore_html = false ) {
 254      global $shortcode_tags;
 255  
 256      if ( ! str_contains( $content, '[' ) ) {
 257          return $content;
 258      }
 259  
 260      if ( empty( $shortcode_tags ) || ! is_array( $shortcode_tags ) ) {
 261          return $content;
 262      }
 263  
 264      // Find all registered tag names in $content.
 265      preg_match_all( '@\[([^<>&/\[\]\x00-\x20=]++)@', $content, $matches );
 266      $tagnames = array_intersect( array_keys( $shortcode_tags ), $matches[1] );
 267  
 268      if ( empty( $tagnames ) ) {
 269          return $content;
 270      }
 271  
 272      // Ensure this context is only added once if shortcodes are nested.
 273      $has_filter   = has_filter( 'wp_get_attachment_image_context', '_filter_do_shortcode_context' );
 274      $filter_added = false;
 275  
 276      if ( ! $has_filter ) {
 277          $filter_added = add_filter( 'wp_get_attachment_image_context', '_filter_do_shortcode_context' );
 278      }
 279  
 280      $content = do_shortcodes_in_html_tags( $content, $ignore_html, $tagnames );
 281  
 282      $pattern = get_shortcode_regex( $tagnames );
 283      $content = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $content );
 284  
 285      // Always restore square braces so we don't break things like <!--[if IE ]>.
 286      $content = unescape_invalid_shortcodes( $content );
 287  
 288      // Only remove the filter if it was added in this scope.
 289      if ( $filter_added ) {
 290          remove_filter( 'wp_get_attachment_image_context', '_filter_do_shortcode_context' );
 291      }
 292  
 293      return $content;
 294  }
 295  
 296  /**
 297   * Filter the `wp_get_attachment_image_context` hook during shortcode rendering.
 298   *
 299   * When wp_get_attachment_image() is called during shortcode rendering, we need to make clear
 300   * that the context is a shortcode and not part of the theme's template rendering logic.
 301   *
 302   * @since 6.3.0
 303   * @access private
 304   *
 305   * @return string The filtered context value for wp_get_attachment_images when doing shortcodes.
 306   */
 307  function _filter_do_shortcode_context() {
 308      return 'do_shortcode';
 309  }
 310  
 311  /**
 312   * Retrieves the shortcode regular expression for searching.
 313   *
 314   * The regular expression combines the shortcode tags in the regular expression
 315   * in a regex class.
 316   *
 317   * The regular expression contains 6 different sub matches to help with parsing.
 318   *
 319   * 1 - An extra [ to allow for escaping shortcodes with double [[]]
 320   * 2 - The shortcode name
 321   * 3 - The shortcode argument list
 322   * 4 - The self closing /
 323   * 5 - The content of a shortcode when it wraps some content.
 324   * 6 - An extra ] to allow for escaping shortcodes with double [[]]
 325   *
 326   * @since 2.5.0
 327   * @since 4.4.0 Added the `$tagnames` parameter.
 328   *
 329   * @global array $shortcode_tags
 330   *
 331   * @param array $tagnames Optional. List of shortcodes to find. Defaults to all registered shortcodes.
 332   * @return string The shortcode search regular expression.
 333   *
 334   * @phpstan-return non-falsy-string
 335   */
 336  function get_shortcode_regex( $tagnames = null ) {
 337      global $shortcode_tags;
 338  
 339      if ( empty( $tagnames ) ) {
 340          $tagnames = array_keys( $shortcode_tags );
 341      }
 342      $tagregexp = implode( '|', array_map( 'preg_quote', $tagnames ) );
 343  
 344      /*
 345       * WARNING! Do not change this regex without changing do_shortcode_tag() and strip_shortcode_tag().
 346       * Also, see shortcode_unautop() and shortcode.js.
 347       */
 348  
 349      // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
 350      return '\\['                             // Opening bracket.
 351          . '(\\[?)'                           // 1: Optional second opening bracket for escaping shortcodes: [[tag]].
 352          . "($tagregexp)"                     // 2: Shortcode name.
 353          . '(?![\\w-])'                       // Not followed by word character or hyphen.
 354          . '('                                // 3: Unroll the loop: Inside the opening shortcode tag.
 355          .     '[^\\]\\/]*'                   // Not a closing bracket or forward slash.
 356          .     '(?:'
 357          .         '\\/(?!\\])'               // A forward slash not followed by a closing bracket.
 358          .         '[^\\]\\/]*'               // Not a closing bracket or forward slash.
 359          .     ')*?'
 360          . ')'
 361          . '(?:'
 362          .     '(\\/)'                        // 4: Self closing tag...
 363          .     '\\]'                          // ...and closing bracket.
 364          . '|'
 365          .     '\\]'                          // Closing bracket.
 366          .     '(?:'
 367          .         '('                        // 5: Unroll the loop: Optionally, anything between the opening and closing shortcode tags.
 368          .             '[^\\[]*+'             // Not an opening bracket.
 369          .             '(?:'
 370          .                 '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag.
 371          .                 '[^\\[]*+'         // Not an opening bracket.
 372          .             ')*+'
 373          .         ')'
 374          .         '\\[\\/\\2\\]'             // Closing shortcode tag.
 375          .     ')?'
 376          . ')'
 377          . '(\\]?)';                          // 6: Optional second closing bracket for escaping shortcodes: [[tag]].
 378      // phpcs:enable
 379  }
 380  
 381  /**
 382   * Regular Expression callable for do_shortcode() for calling shortcode hook.
 383   *
 384   * @see get_shortcode_regex() for details of the match array contents.
 385   *
 386   * @since 2.5.0
 387   * @access private
 388   *
 389   * @global array $shortcode_tags
 390   *
 391   * @param array $m {
 392   *     Regular expression match array.
 393   *
 394   *     @type string $0 Entire matched shortcode text.
 395   *     @type string $1 Optional second opening bracket for escaping shortcodes.
 396   *     @type string $2 Shortcode name.
 397   *     @type string $3 Shortcode arguments list.
 398   *     @type string $4 Optional self closing slash.
 399   *     @type string $5 Content of a shortcode when it wraps some content.
 400   *     @type string $6 Optional second closing bracket for escaping shortcodes.
 401   * }
 402   * @return string Shortcode output.
 403   */
 404  function do_shortcode_tag( $m ) {
 405      global $shortcode_tags;
 406  
 407      // Allow [[foo]] syntax for escaping a tag.
 408      if ( '[' === $m[1] && ']' === $m[6] ) {
 409          return substr( $m[0], 1, -1 );
 410      }
 411  
 412      $tag  = $m[2];
 413      $attr = shortcode_parse_atts( $m[3] );
 414  
 415      if ( ! is_callable( $shortcode_tags[ $tag ] ) ) {
 416          _doing_it_wrong(
 417              __FUNCTION__,
 418              /* translators: %s: Shortcode tag. */
 419              sprintf( __( 'Attempting to parse a shortcode without a valid callback: %s' ), $tag ),
 420              '4.3.0'
 421          );
 422          return $m[0];
 423      }
 424  
 425      /**
 426       * Filters whether to call a shortcode callback.
 427       *
 428       * Returning a non-false value from filter will short-circuit the
 429       * shortcode generation process, returning that value instead.
 430       *
 431       * @since 4.7.0
 432       * @since 6.5.0 The `$attr` parameter is always an array.
 433       *
 434       * @param false|string $output Short-circuit return value. Either false or the value to replace the shortcode with.
 435       * @param string       $tag    Shortcode name.
 436       * @param array        $attr   Shortcode attributes array, can be empty if the original arguments string cannot be parsed.
 437       * @param array        $m      Regular expression match array.
 438       */
 439      $return = apply_filters( 'pre_do_shortcode_tag', false, $tag, $attr, $m );
 440      if ( false !== $return ) {
 441          return $return;
 442      }
 443  
 444      $content = $m[5] ?? null;
 445  
 446      $output = $m[1] . call_user_func( $shortcode_tags[ $tag ], $attr, $content, $tag ) . $m[6];
 447  
 448      /**
 449       * Filters the output created by a shortcode callback.
 450       *
 451       * @since 4.7.0
 452       * @since 6.5.0 The `$attr` parameter is always an array.
 453       *
 454       * @param string $output Shortcode output.
 455       * @param string $tag    Shortcode name.
 456       * @param array  $attr   Shortcode attributes array, can be empty if the original arguments string cannot be parsed.
 457       * @param array  $m      Regular expression match array.
 458       */
 459      return apply_filters( 'do_shortcode_tag', $output, $tag, $attr, $m );
 460  }
 461  
 462  /**
 463   * Searches only inside HTML elements for shortcodes and process them.
 464   *
 465   * Any [ or ] characters remaining inside elements will be HTML encoded
 466   * to prevent interference with shortcodes that are outside the elements.
 467   * Assumes $content processed by KSES already.  Users with unfiltered_html
 468   * capability may get unexpected output if angle braces are nested in tags.
 469   *
 470   * @since 4.2.3
 471   *
 472   * @param string $content     Content to search for shortcodes.
 473   * @param bool   $ignore_html When true, all square braces inside elements will be encoded.
 474   * @param array  $tagnames    List of shortcodes to find.
 475   * @return string Content with shortcodes filtered out.
 476   */
 477  function do_shortcodes_in_html_tags( $content, $ignore_html, $tagnames ) {
 478      // Normalize entities in unfiltered HTML before adding placeholders.
 479      $trans   = array(
 480          '&#91;' => '&#091;',
 481          '&#93;' => '&#093;',
 482      );
 483      $content = strtr( $content, $trans );
 484      $trans   = array(
 485          '[' => '&#91;',
 486          ']' => '&#93;',
 487      );
 488  
 489      $pattern = get_shortcode_regex( $tagnames );
 490      $textarr = wp_html_split( $content );
 491  
 492      foreach ( $textarr as &$element ) {
 493          if ( '' === $element || '<' !== $element[0] ) {
 494              continue;
 495          }
 496  
 497          $noopen  = ! str_contains( $element, '[' );
 498          $noclose = ! str_contains( $element, ']' );
 499          if ( $noopen || $noclose ) {
 500              // This element does not contain shortcodes.
 501              if ( $noopen xor $noclose ) {
 502                  // Need to encode stray '[' or ']' chars.
 503                  $element = strtr( $element, $trans );
 504              }
 505              continue;
 506          }
 507  
 508          if ( $ignore_html || str_starts_with( $element, '<!--' ) || str_starts_with( $element, '<![CDATA[' ) ) {
 509              // Encode all '[' and ']' chars.
 510              $element = strtr( $element, $trans );
 511              continue;
 512          }
 513  
 514          $attributes = wp_kses_attr_parse( $element );
 515          if ( false === $attributes ) {
 516              // Some plugins are doing things like [name] <[email]>.
 517              if ( 1 === preg_match( '%^<\s*\[\[?[^\[\]]+\]%', $element ) ) {
 518                  $element = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $element );
 519              }
 520  
 521              // Looks like we found some unexpected unfiltered HTML. Skipping it for confidence.
 522              $element = strtr( $element, $trans );
 523              continue;
 524          }
 525  
 526          // Get element name.
 527          $front   = array_shift( $attributes );
 528          $back    = array_pop( $attributes );
 529          $matches = array();
 530          preg_match( '%[a-zA-Z0-9]+%', $front, $matches );
 531          $elname = $matches[0];
 532  
 533          // Look for shortcodes in each attribute separately.
 534          foreach ( $attributes as &$attr ) {
 535              $open  = strpos( $attr, '[' );
 536              $close = strpos( $attr, ']' );
 537              if ( false === $open || false === $close ) {
 538                  continue; // Go to next attribute. Square braces will be escaped at end of loop.
 539              }
 540              $double = strpos( $attr, '"' );
 541              $single = strpos( $attr, "'" );
 542              if ( ( false === $single || $open < $single ) && ( false === $double || $open < $double ) ) {
 543                  /*
 544                   * $attr like '[shortcode]' or 'name = [shortcode]' implies unfiltered_html.
 545                   * In this specific situation we assume KSES did not run because the input
 546                   * was written by an administrator, so we should avoid changing the output
 547                   * and we do not need to run KSES here.
 548                   */
 549                  $attr = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $attr );
 550              } else {
 551                  /*
 552                   * $attr like 'name = "[shortcode]"' or "name = '[shortcode]'".
 553                   * We do not know if $content was unfiltered. Assume KSES ran before shortcodes.
 554                   */
 555                  $count    = 0;
 556                  $new_attr = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $attr, -1, $count );
 557                  if ( $count > 0 ) {
 558                      // Sanitize the shortcode output using KSES.
 559                      $new_attr = wp_kses_one_attr( $new_attr, $elname );
 560                      if ( '' !== trim( $new_attr ) ) {
 561                          // The shortcode is safe to use now.
 562                          $attr = $new_attr;
 563                      }
 564                  }
 565              }
 566          }
 567          $element = $front . implode( '', $attributes ) . $back;
 568  
 569          // Now encode any remaining '[' or ']' chars.
 570          $element = strtr( $element, $trans );
 571      }
 572  
 573      $content = implode( '', $textarr );
 574  
 575      return $content;
 576  }
 577  
 578  /**
 579   * Removes placeholders added by do_shortcodes_in_html_tags().
 580   *
 581   * @since 4.2.3
 582   *
 583   * @param string $content Content to search for placeholders.
 584   * @return string Content with placeholders removed.
 585   */
 586  function unescape_invalid_shortcodes( $content ) {
 587      // Clean up entire string, avoids re-parsing HTML.
 588      $trans = array(
 589          '&#91;' => '[',
 590          '&#93;' => ']',
 591      );
 592  
 593      $content = strtr( $content, $trans );
 594  
 595      return $content;
 596  }
 597  
 598  /**
 599   * Retrieves the shortcode attributes regex.
 600   *
 601   * @since 4.4.0
 602   *
 603   * @return string The shortcode attribute regular expression.
 604   *
 605   * @phpstan-return non-falsy-string
 606   */
 607  function get_shortcode_atts_regex() {
 608      return '/([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*\'([^\']*)\'(?:\s|$)|([\w-]+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|\'([^\']*)\'(?:\s|$)|(\S+)(?:\s|$)/';
 609  }
 610  
 611  /**
 612   * Retrieves all attributes from the shortcodes tag.
 613   *
 614   * The attributes list has the attribute name as the key and the value of the
 615   * attribute as the value in the key/value pair. This allows for easier
 616   * retrieval of the attributes, since all attributes have to be known.
 617   *
 618   * @since 2.5.0
 619   * @since 6.5.0 The function now always returns an array,
 620   *              even if the original arguments string cannot be parsed or is empty.
 621   * @since 7.1.5 A hex or octal escape that decodes to <, >, " or ' produces a character reference.
 622   *
 623   * @param string $text Shortcode arguments list.
 624   * @return array Array of attribute values keyed by attribute name.
 625   *               Returns empty array if there are no attributes
 626   *               or if the original arguments string cannot be parsed.
 627   */
 628  function shortcode_parse_atts( $text ) {
 629      // Decodes like stripcslashes(), except that a hex or octal escape that decodes
 630      // to `<`, `>`, `"` or `'` produces `&lt;`, `&gt;`, `&quot;` or `&#039;`.
 631      $decode = static function ( $value ) {
 632          if ( ! str_contains( $value, '\\' ) ) {
 633              return $value;
 634          }
 635  
 636          return preg_replace_callback(
 637              '/\\\\(?:x[0-9A-Fa-f]{1,2}|[0-7]{1,3}|.)/s',
 638              static function ( $matches ) {
 639                  $decoded = stripcslashes( $matches[0] );
 640  
 641                  // A two-byte escape cannot decode to a structural character that the raw value lacks.
 642                  if ( 2 === strlen( $matches[0] ) ) {
 643                      return $decoded;
 644                  }
 645  
 646                  $structural = array(
 647                      '<' => '&lt;',
 648                      '>' => '&gt;',
 649                      '"' => '&quot;',
 650                      "'" => '&#039;',
 651                  );
 652  
 653                  return $structural[ $decoded ] ?? $decoded;
 654              },
 655              $value
 656          );
 657      };
 658  
 659      $atts    = array();
 660      $pattern = get_shortcode_atts_regex();
 661      $text    = preg_replace( "/[\x{00a0}\x{200b}]+/u", ' ', $text );
 662      if ( preg_match_all( $pattern, $text, $match, PREG_SET_ORDER ) ) {
 663          foreach ( $match as $m ) {
 664              if ( ! empty( $m[1] ) ) {
 665                  $atts[ strtolower( $m[1] ) ] = $decode( $m[2] );
 666              } elseif ( ! empty( $m[3] ) ) {
 667                  $atts[ strtolower( $m[3] ) ] = $decode( $m[4] );
 668              } elseif ( ! empty( $m[5] ) ) {
 669                  $atts[ strtolower( $m[5] ) ] = $decode( $m[6] );
 670              } elseif ( isset( $m[7] ) && strlen( $m[7] ) ) {
 671                  $atts[] = $decode( $m[7] );
 672              } elseif ( isset( $m[8] ) && strlen( $m[8] ) ) {
 673                  $atts[] = $decode( $m[8] );
 674              } elseif ( isset( $m[9] ) ) {
 675                  $atts[] = $decode( $m[9] );
 676              }
 677          }
 678  
 679          // Reject any unclosed HTML elements.
 680          foreach ( $atts as &$value ) {
 681              if ( str_contains( $value, '<' ) ) {
 682                  if ( 1 !== preg_match( '/^[^<]*+(?:<[^>]*+>[^<]*+)*+$/', $value ) ) {
 683                      $value = '';
 684                  }
 685              }
 686          }
 687      }
 688  
 689      return $atts;
 690  }
 691  
 692  /**
 693   * Combines user attributes with known attributes and fill in defaults when needed.
 694   *
 695   * The pairs should be considered to be all of the attributes which are
 696   * supported by the caller and given as a list. The returned attributes will
 697   * only contain the attributes in the $pairs list.
 698   *
 699   * If the $atts list has unsupported attributes, then they will be ignored and
 700   * removed from the final returned list.
 701   *
 702   * @since 2.5.0
 703   *
 704   * @param array  $pairs     Entire list of supported attributes and their defaults.
 705   * @param array  $atts      User defined attributes in shortcode tag.
 706   * @param string $shortcode Optional. The name of the shortcode, provided for context to enable filtering
 707   * @return array Combined and filtered attribute list.
 708   */
 709  function shortcode_atts( $pairs, $atts, $shortcode = '' ) {
 710      $atts = (array) $atts;
 711      $out  = array();
 712      foreach ( $pairs as $name => $default ) {
 713          if ( array_key_exists( $name, $atts ) ) {
 714              $out[ $name ] = $atts[ $name ];
 715          } else {
 716              $out[ $name ] = $default;
 717          }
 718      }
 719  
 720      if ( $shortcode ) {
 721          /**
 722           * Filters shortcode attributes.
 723           *
 724           * If the third parameter of the shortcode_atts() function is present then this filter is available.
 725           * The third parameter, $shortcode, is the name of the shortcode.
 726           *
 727           * @since 3.6.0
 728           * @since 4.4.0 Added the `$shortcode` parameter.
 729           *
 730           * @param array  $out       The output array of shortcode attributes.
 731           * @param array  $pairs     The supported attributes and their defaults.
 732           * @param array  $atts      The user defined shortcode attributes.
 733           * @param string $shortcode The shortcode name.
 734           */
 735          $out = apply_filters( "shortcode_atts_{$shortcode}", $out, $pairs, $atts, $shortcode );
 736      }
 737  
 738      return $out;
 739  }
 740  
 741  /**
 742   * Removes all shortcode tags from the given content.
 743   *
 744   * @since 2.5.0
 745   *
 746   * @global array $shortcode_tags
 747   *
 748   * @param string $content Content to remove shortcode tags.
 749   * @return string Content without shortcode tags.
 750   */
 751  function strip_shortcodes( $content ) {
 752      global $shortcode_tags;
 753  
 754      if ( ! str_contains( $content, '[' ) ) {
 755          return $content;
 756      }
 757  
 758      if ( empty( $shortcode_tags ) || ! is_array( $shortcode_tags ) ) {
 759          return $content;
 760      }
 761  
 762      // Find all registered tag names in $content.
 763      preg_match_all( '@\[([^<>&/\[\]\x00-\x20=]++)@', $content, $matches );
 764  
 765      $tags_to_remove = array_keys( $shortcode_tags );
 766  
 767      /**
 768       * Filters the list of shortcode tags to remove from the content.
 769       *
 770       * @since 4.7.0
 771       *
 772       * @param array  $tags_to_remove Array of shortcode tags to remove.
 773       * @param string $content        Content shortcodes are being removed from.
 774       */
 775      $tags_to_remove = apply_filters( 'strip_shortcodes_tagnames', $tags_to_remove, $content );
 776  
 777      $tagnames = array_intersect( $tags_to_remove, $matches[1] );
 778  
 779      if ( empty( $tagnames ) ) {
 780          return $content;
 781      }
 782  
 783      $content = do_shortcodes_in_html_tags( $content, true, $tagnames );
 784  
 785      $pattern = get_shortcode_regex( $tagnames );
 786      $content = preg_replace_callback( "/$pattern/", 'strip_shortcode_tag', $content );
 787  
 788      // Always restore square braces so we don't break things like <!--[if IE ]>.
 789      $content = unescape_invalid_shortcodes( $content );
 790  
 791      return $content;
 792  }
 793  
 794  /**
 795   * Strips a shortcode tag based on RegEx matches against post content.
 796   *
 797   * @since 3.3.0
 798   *
 799   * @param array $m RegEx matches against post content.
 800   * @return string|false The content stripped of the tag, otherwise false.
 801   */
 802  function strip_shortcode_tag( $m ) {
 803      // Allow [[foo]] syntax for escaping a tag.
 804      if ( '[' === $m[1] && ']' === $m[6] ) {
 805          return substr( $m[0], 1, -1 );
 806      }
 807  
 808      return $m[1] . $m[6];
 809  }


Generated : Fri Dec 4 08:20:01 2026 Cross-referenced by PHPXref