[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> functions.wp-scripts.php (source)

   1  <?php
   2  /**
   3   * Dependencies API: Scripts functions
   4   *
   5   * @since 2.6.0
   6   *
   7   * @package WordPress
   8   * @subpackage Dependencies
   9   */
  10  
  11  /**
  12   * Initializes $wp_scripts if it has not been set.
  13   *
  14   * @since 4.2.0
  15   *
  16   * @global WP_Scripts $wp_scripts
  17   *
  18   * @return WP_Scripts WP_Scripts instance.
  19   */
  20  function wp_scripts() {
  21      global $wp_scripts;
  22  
  23      if ( ! ( $wp_scripts instanceof WP_Scripts ) ) {
  24          $wp_scripts = new WP_Scripts();
  25      }
  26  
  27      return $wp_scripts;
  28  }
  29  
  30  /**
  31   * Helper function to output a _doing_it_wrong message when applicable.
  32   *
  33   * @ignore
  34   * @since 4.2.0
  35   * @since 5.5.0 Added the `$handle` parameter.
  36   *
  37   * @param string $function_name Function name.
  38   * @param string $handle        Optional. Name of the script or stylesheet that was
  39   *                              registered or enqueued too early. Default empty.
  40   */
  41  function _wp_scripts_maybe_doing_it_wrong( $function_name, $handle = '' ) {
  42      if ( did_action( 'init' ) || did_action( 'wp_enqueue_scripts' )
  43          || did_action( 'admin_enqueue_scripts' ) || did_action( 'login_enqueue_scripts' )
  44      ) {
  45          return;
  46      }
  47  
  48      $message = sprintf(
  49          /* translators: 1: wp_enqueue_scripts, 2: admin_enqueue_scripts, 3: login_enqueue_scripts */
  50          __( 'Scripts and styles should not be registered or enqueued until the %1$s, %2$s, or %3$s hooks.' ),
  51          '<code>wp_enqueue_scripts</code>',
  52          '<code>admin_enqueue_scripts</code>',
  53          '<code>login_enqueue_scripts</code>'
  54      );
  55  
  56      if ( $handle ) {
  57          $message .= ' ' . sprintf(
  58              /* translators: %s: Name of the script or stylesheet. */
  59              __( 'This notice was triggered by the %s handle.' ),
  60              '<code>' . $handle . '</code>'
  61          );
  62      }
  63  
  64      _doing_it_wrong(
  65          $function_name,
  66          $message,
  67          '3.3.0'
  68      );
  69  }
  70  
  71  /**
  72   * Adds the data for the recognized args and warns for unrecognized args.
  73   *
  74   * @see wp_enqueue_script()
  75   * @see wp_register_script()
  76   *
  77   * @ignore
  78   * @since 7.0.0
  79   *
  80   * @param WP_Scripts $wp_scripts WP_Scripts instance.
  81   * @param string     $handle     Script handle.
  82   * @param array      $args       Array of extra args for the script.
  83   *
  84   * @phpstan-param non-empty-string $handle
  85   * @phpstan-param array{
  86   *     in_footer?: bool,
  87   *     strategy?: 'async'|'defer',
  88   *     fetchpriority?: 'low'|'auto'|'high',
  89   *     module_dependencies?: array<non-empty-string|array{ id: non-empty-string, ... }>,
  90   * } $args
  91   */
  92  function _wp_scripts_add_args_data( WP_Scripts $wp_scripts, string $handle, array $args ): void {
  93      $allowed_keys = array( 'strategy', 'in_footer', 'fetchpriority', 'module_dependencies' );
  94      $unknown_keys = array_diff( array_keys( $args ), $allowed_keys );
  95      if ( ! empty( $unknown_keys ) ) {
  96          $trace         = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 );
  97          $function_name = ( $trace[1]['class'] ?? '' ) . ( $trace[1]['type'] ?? '' ) . ( $trace[1]['function'] ?? __FUNCTION__ );
  98          _doing_it_wrong(
  99              $function_name,
 100              sprintf(
 101                  /* translators: 1: $args, 2: List of unrecognized keys, 3: List of supported keys. */
 102                  __( 'Unrecognized key(s) in the %1$s param: %2$s. Supported keys: %3$s' ),
 103                  '$args',
 104                  implode( wp_get_list_item_separator(), $unknown_keys ),
 105                  implode( wp_get_list_item_separator(), $allowed_keys )
 106              ),
 107              '7.0.0'
 108          );
 109      }
 110  
 111      $in_footer = ! empty( $args['in_footer'] );
 112      if ( $in_footer ) {
 113          $wp_scripts->add_data( $handle, 'group', 1 );
 114      }
 115      if ( ! empty( $args['strategy'] ) ) {
 116          $wp_scripts->add_data( $handle, 'strategy', $args['strategy'] );
 117      }
 118      if ( ! empty( $args['fetchpriority'] ) ) {
 119          $wp_scripts->add_data( $handle, 'fetchpriority', $args['fetchpriority'] );
 120      }
 121      if ( ! empty( $args['module_dependencies'] ) ) {
 122          $wp_scripts->add_data( $handle, 'module_dependencies', $args['module_dependencies'] );
 123  
 124          /*
 125           * A classic script with module dependencies must either be printed in the
 126           * footer or use the 'defer' loading strategy. Otherwise, the script may be
 127           * evaluated before the script modules import map is printed, causing
 128           * dynamic imports to fail with a "Failed to resolve module specifier" error.
 129           */
 130          $is_deferred = 'defer' === ( $args['strategy'] ?? null );
 131          if ( ! $in_footer && ! $is_deferred ) {
 132              $trace         = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 );
 133              $function_name = ( $trace[1]['class'] ?? '' ) . ( $trace[1]['type'] ?? '' ) . ( $trace[1]['function'] ?? __FUNCTION__ );
 134              _doing_it_wrong(
 135                  $function_name,
 136                  sprintf(
 137                      /* translators: 1: 'module_dependencies', 2: Script handle, 3: 'in_footer', 4: 'strategy', 5: 'defer'. */
 138                      __( 'When the %1$s arg is provided, the "%2$s" script must either be printed in the footer (%3$s set to true) or use a deferred loading %4$s (%5$s) so that the import map is printed before the script is evaluated.' ),
 139                      '<code>module_dependencies</code>',
 140                      $handle,
 141                      '<code>in_footer</code>',
 142                      '<code>strategy</code>',
 143                      '<code>defer</code>'
 144                  ),
 145                  '7.0.0'
 146              );
 147          }
 148      }
 149  }
 150  
 151  /**
 152   * Prints scripts in document head that are in the $handles queue.
 153   *
 154   * Called by admin-header.php and {@see 'wp_head'} hook. Since it is called by wp_head on every page load,
 155   * the function does not instantiate the WP_Scripts object unless script names are explicitly passed.
 156   * Makes use of already-instantiated `$wp_scripts` global if present. Use provided {@see 'wp_print_scripts'}
 157   * hook to register/enqueue new scripts.
 158   *
 159   * @see WP_Scripts::do_item()
 160   * @since 2.1.0
 161   *
 162   * @global WP_Scripts $wp_scripts The WP_Scripts object for printing scripts.
 163   *
 164   * @param string|string[]|false $handles Optional. Scripts to be printed. Default 'false'.
 165   * @return string[] On success, an array of handles of processed WP_Dependencies items; otherwise, an empty array.
 166   */
 167  function wp_print_scripts( $handles = false ) {
 168      global $wp_scripts;
 169  
 170      /**
 171       * Fires before scripts in the $handles queue are printed.
 172       *
 173       * @since 2.1.0
 174       */
 175      do_action( 'wp_print_scripts' );
 176  
 177      if ( '' === $handles ) { // For 'wp_head'.
 178          $handles = false;
 179      }
 180  
 181      _wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
 182  
 183      if ( ! ( $wp_scripts instanceof WP_Scripts ) ) {
 184          if ( ! $handles ) {
 185              return array(); // No need to instantiate if nothing is there.
 186          }
 187      }
 188  
 189      return wp_scripts()->do_items( $handles );
 190  }
 191  
 192  /**
 193   * Adds extra code to a registered script.
 194   *
 195   * Code will only be added if the script is already in the queue.
 196   * Accepts a string `$data` containing the code. If two or more code blocks
 197   * are added to the same script `$handle`, they will be printed in the order
 198   * they were added, i.e. the latter added code can redeclare the previous.
 199   *
 200   * @since 4.5.0
 201   *
 202   * @see WP_Scripts::add_inline_script()
 203   *
 204   * @param string $handle   Name of the script to add the inline script to.
 205   * @param string $data     String containing the JavaScript to be added.
 206   * @param string $position Optional. Whether to add the inline script before the handle
 207   *                         or after. Default 'after'.
 208   * @return bool True on success, false on failure.
 209   */
 210  function wp_add_inline_script( $handle, $data, $position = 'after' ) {
 211      _wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle );
 212  
 213      if ( false !== stripos( $data, '</script>' ) ) {
 214          _doing_it_wrong(
 215              __FUNCTION__,
 216              sprintf(
 217                  /* translators: 1: <script>, 2: wp_add_inline_script() */
 218                  __( 'Do not pass %1$s tags to %2$s.' ),
 219                  '<code>&lt;script&gt;</code>',
 220                  '<code>wp_add_inline_script()</code>'
 221              ),
 222              '4.5.0'
 223          );
 224          $data = trim( (string) preg_replace( '#<script[^>]*>(.*)</script>#is', '$1', $data ) );
 225      }
 226  
 227      return wp_scripts()->add_inline_script( $handle, $data, $position );
 228  }
 229  
 230  /**
 231   * Registers a new script.
 232   *
 233   * Registers a script to be enqueued later using the wp_enqueue_script() function.
 234   *
 235   * @see WP_Dependencies::add()
 236   * @see WP_Dependencies::add_data()
 237   *
 238   * @since 2.1.0
 239   * @since 4.3.0 A return value was added.
 240   * @since 6.3.0 The $in_footer parameter of type boolean was overloaded to be an $args parameter of type array.
 241   * @since 6.9.0 The $fetchpriority parameter of type string was added to the $args parameter of type array.
 242   * @since 7.0.0 The $module_dependencies parameter of type string[] was added to the $args parameter of type array.
 243   *
 244   * @param string           $handle Name of the script. Should be unique.
 245   * @param string|false     $src    Full URL of the script, or path of the script relative to the WordPress root directory.
 246   *                                 If source is set to false, script is an alias of other scripts it depends on.
 247   * @param string[]         $deps   Optional. An array of registered script handles this script depends on. Default empty array.
 248   * @param string|bool|null $ver    Optional. String specifying script version number, if it has one, which is added to the URL
 249   *                                 as a query string for cache busting purposes. If version is set to false, a version
 250   *                                 number is automatically added equal to current installed WordPress version.
 251   *                                 If set to null, no version is added.
 252   * @param array|bool       $args   {
 253   *     Optional. An array of extra args for the script. Default empty array.
 254   *     Otherwise, it may be a boolean in which case it determines whether the script is printed in the footer. Default false.
 255   *
 256   *     @type string $strategy            Optional. If provided, may be either 'defer' or 'async'.
 257   *     @type bool   $in_footer           Optional. Whether to print the script in the footer. Default 'false'.
 258   *     @type string $fetchpriority       Optional. The fetch priority for the script. Default 'auto'.
 259   *     @type array  $module_dependencies Optional. IDs for module dependencies loaded via dynamic import. Default empty array.
 260   *                                                                    For the full data format, see the `$deps` param of {@see wp_register_script_module()}.
 261   *                                                                    When provided, the script must either be printed in the footer (with
 262   *                                                                    `in_footer` set to true) or use a deferred loading `strategy` (`defer`),
 263   *                                                                    so that the script modules import map is printed before the script
 264   *                                                                    is evaluated. Otherwise dynamic imports may fail to resolve.
 265   *                                                                    The translations of these script modules are printed after the scripts
 266   *                                                                    in the footer. A script that is not deferred should import them once
 267   *                                                                    the document has been parsed, so that their translations are available.
 268   * }
 269   * @return bool Whether the script has been registered. True on success, false on failure.
 270   *
 271   * @phpstan-param non-empty-string $handle
 272   * @phpstan-param non-empty-string|false $src
 273   * @phpstan-param non-empty-string[] $deps
 274   * @phpstan-param array{
 275   *     in_footer?: bool,
 276   *     strategy?: 'async'|'defer',
 277   *     fetchpriority?: 'low'|'auto'|'high',
 278   *     module_dependencies?: array<non-empty-string|array{ id: non-empty-string, ... }>,
 279   * }|bool $args
 280   */
 281  function wp_register_script( $handle, $src, $deps = array(), $ver = false, $args = array() ) {
 282      if ( ! is_array( $args ) ) {
 283          $args = array(
 284              'in_footer' => (bool) $args,
 285          );
 286      }
 287      _wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle );
 288  
 289      $wp_scripts = wp_scripts();
 290  
 291      $registered = $wp_scripts->add( $handle, $src, $deps, $ver );
 292      _wp_scripts_add_args_data( $wp_scripts, $handle, $args );
 293  
 294      return $registered;
 295  }
 296  
 297  /**
 298   * Localizes a script.
 299   *
 300   * Works only if the script has already been registered.
 301   *
 302   * Accepts an associative array `$l10n` and creates a JavaScript object:
 303   *
 304   *     "$object_name": {
 305   *         key: value,
 306   *         key: value,
 307   *         ...
 308   *     }
 309   *
 310   * @see WP_Scripts::localize()
 311   * @link https://core.trac.wordpress.org/ticket/11520
 312   *
 313   * @since 2.2.0
 314   *
 315   * @todo Documentation cleanup
 316   *
 317   * @param string               $handle      Script handle the data will be attached to.
 318   * @param string               $object_name Name for the JavaScript object. Passed directly, so it should be qualified JS variable.
 319   *                                          Example: '/[a-zA-Z0-9_]+/'.
 320   * @param array<string, mixed> $l10n        The data itself. The data can be either a single or multi-dimensional array.
 321   * @return bool True if the script was successfully localized, false otherwise.
 322   */
 323  function wp_localize_script( $handle, $object_name, $l10n ) {
 324      $wp_scripts = wp_scripts();
 325  
 326      return $wp_scripts->localize( $handle, $object_name, $l10n );
 327  }
 328  
 329  /**
 330   * Sets translated strings for a script.
 331   *
 332   * Works only if the script has already been registered.
 333   *
 334   * @see WP_Scripts::set_translations()
 335   * @since 5.0.0
 336   * @since 5.1.0 The `$domain` parameter was made optional.
 337   *
 338   * @global WP_Scripts $wp_scripts The WP_Scripts object for printing scripts.
 339   *
 340   * @param string $handle Script handle the textdomain will be attached to.
 341   * @param string $domain Optional. Text domain. Default 'default'.
 342   * @param string $path   Optional. The full file path to the directory containing translation files.
 343   * @return bool True if the text domain was successfully localized, false otherwise.
 344   */
 345  function wp_set_script_translations( $handle, $domain = 'default', $path = '' ) {
 346      global $wp_scripts;
 347  
 348      if ( ! ( $wp_scripts instanceof WP_Scripts ) ) {
 349          _wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle );
 350          return false;
 351      }
 352  
 353      return $wp_scripts->set_translations( $handle, $domain, $path );
 354  }
 355  
 356  /**
 357   * Removes a registered script.
 358   *
 359   * Note: there are intentional safeguards in place to prevent critical admin scripts,
 360   * such as jQuery core, from being unregistered.
 361   *
 362   * @see WP_Dependencies::remove()
 363   *
 364   * @since 2.1.0
 365   *
 366   * @global string $pagenow The filename of the current screen.
 367   *
 368   * @param string $handle Name of the script to be removed.
 369   */
 370  function wp_deregister_script( $handle ) {
 371      global $pagenow;
 372  
 373      _wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle );
 374  
 375      /**
 376       * Do not allow accidental or negligent de-registering of critical scripts in the admin.
 377       * Show minimal remorse if the correct hook is used.
 378       */
 379      $current_filter = current_filter();
 380      if ( ( is_admin() && 'admin_enqueue_scripts' !== $current_filter ) ||
 381          ( 'wp-login.php' === $pagenow && 'login_enqueue_scripts' !== $current_filter )
 382      ) {
 383          $not_allowed = array(
 384              'jquery',
 385              'jquery-core',
 386              'jquery-migrate',
 387              'jquery-ui-core',
 388              'jquery-ui-accordion',
 389              'jquery-ui-autocomplete',
 390              'jquery-ui-button',
 391              'jquery-ui-datepicker',
 392              'jquery-ui-dialog',
 393              'jquery-ui-draggable',
 394              'jquery-ui-droppable',
 395              'jquery-ui-menu',
 396              'jquery-ui-mouse',
 397              'jquery-ui-position',
 398              'jquery-ui-progressbar',
 399              'jquery-ui-resizable',
 400              'jquery-ui-selectable',
 401              'jquery-ui-slider',
 402              'jquery-ui-sortable',
 403              'jquery-ui-spinner',
 404              'jquery-ui-tabs',
 405              'jquery-ui-tooltip',
 406              'jquery-ui-widget',
 407              'underscore',
 408              'backbone',
 409          );
 410  
 411          if ( in_array( $handle, $not_allowed, true ) ) {
 412              _doing_it_wrong(
 413                  __FUNCTION__,
 414                  sprintf(
 415                      /* translators: 1: Script name, 2: wp_enqueue_scripts */
 416                      __( 'Do not deregister the %1$s script in the administration area. To target the front-end theme, use the %2$s hook.' ),
 417                      "<code>$handle</code>",
 418                      '<code>wp_enqueue_scripts</code>'
 419                  ),
 420                  '3.6.0'
 421              );
 422              return;
 423          }
 424      }
 425  
 426      wp_scripts()->remove( $handle );
 427  }
 428  
 429  /**
 430   * Enqueues a script.
 431   *
 432   * Registers the script if `$src` provided (does NOT overwrite), and enqueues it.
 433   *
 434   * @see WP_Dependencies::add()
 435   * @see WP_Dependencies::add_data()
 436   * @see WP_Dependencies::enqueue()
 437   *
 438   * @since 2.1.0
 439   * @since 6.3.0 The $in_footer parameter of type boolean was overloaded to be an $args parameter of type array.
 440   * @since 6.9.0 The $fetchpriority parameter of type string was added to the $args parameter of type array.
 441   * @since 7.0.0 The $module_dependencies parameter of type string[] was added to the $args parameter of type array.
 442   *
 443   * @param string           $handle Name of the script. Should be unique.
 444   * @param string           $src    Full URL of the script, or path of the script relative to the WordPress root directory.
 445   *                                 Default empty.
 446   * @param string[]         $deps   Optional. An array of registered script handles this script depends on. Default empty array.
 447   * @param string|bool|null $ver    Optional. String specifying script version number, if it has one, which is added to the URL
 448   *                                 as a query string for cache busting purposes. If version is set to false, a version
 449   *                                 number is automatically added equal to current installed WordPress version.
 450   *                                 If set to null, no version is added.
 451   * @param array|bool       $args {
 452   *     Optional. An array of extra args for the script. Default empty array.
 453   *     Otherwise, it may be a boolean in which case it determines whether the script is printed in the footer. Default false.
 454   *
 455   *     @type string $strategy            Optional. If provided, may be either 'defer' or 'async'.
 456   *     @type bool   $in_footer           Optional. Whether to print the script in the footer. Default 'false'.
 457   *     @type string $fetchpriority       Optional. The fetch priority for the script. Default 'auto'.
 458   *     @type array  $module_dependencies Optional. IDs for module dependencies loaded via dynamic import. Default empty array.
 459   *                                       For the full data format, see the `$deps` param of {@see wp_register_script_module()}.
 460   *                                       When provided, the script must either be printed in the footer (with
 461   *                                       `in_footer` set to true) or use a deferred loading `strategy` (`defer`),
 462   *                                       so that the script modules import map is printed before the script
 463   *                                       is evaluated. Otherwise dynamic imports may fail to resolve.
 464   *                                       The translations of these script modules are printed after the scripts
 465   *                                       in the footer. A script that is not deferred should import them once
 466   *                                       the document has been parsed, so that their translations are available.
 467   * }
 468   *
 469   * @phpstan-param non-empty-string $handle
 470   * @phpstan-param string $src
 471   * @phpstan-param non-empty-string[] $deps
 472   * @phpstan-param array{
 473   *     in_footer?: bool,
 474   *     strategy?: 'async'|'defer',
 475   *     fetchpriority?: 'low'|'auto'|'high',
 476   *     module_dependencies?: array<non-empty-string|array{ id: non-empty-string, ... }>,
 477   * }|bool $args
 478   */
 479  function wp_enqueue_script( $handle, $src = '', $deps = array(), $ver = false, $args = array() ) {
 480      _wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle );
 481  
 482      $wp_scripts = wp_scripts();
 483  
 484      if ( $src || ! empty( $args ) ) {
 485          /** @var array{ 0: non-empty-string, 1?: string } $_handle */
 486          $_handle = explode( '?', $handle );
 487          if ( ! is_array( $args ) ) {
 488              $args = array(
 489                  'in_footer' => (bool) $args,
 490              );
 491          }
 492  
 493          if ( $src ) {
 494              $wp_scripts->add( $_handle[0], $src, $deps, $ver );
 495          }
 496          if ( ! empty( $args ) ) {
 497              _wp_scripts_add_args_data( $wp_scripts, $_handle[0], $args );
 498          }
 499      }
 500  
 501      $wp_scripts->enqueue( $handle );
 502  }
 503  
 504  /**
 505   * Removes a previously enqueued script.
 506   *
 507   * @see WP_Dependencies::dequeue()
 508   *
 509   * @since 3.1.0
 510   *
 511   * @param string $handle Name of the script to be removed.
 512   */
 513  function wp_dequeue_script( $handle ) {
 514      _wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle );
 515  
 516      wp_scripts()->dequeue( $handle );
 517  }
 518  
 519  /**
 520   * Determines whether a script has been added to the queue.
 521   *
 522   * For more information on this and similar theme functions, check out
 523   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
 524   * Conditional Tags} article in the Theme Developer Handbook.
 525   *
 526   * @since 2.8.0
 527   * @since 3.5.0 'enqueued' added as an alias of the 'queue' list.
 528   *
 529   * @param string $handle Name of the script.
 530   * @param string $status Optional. Status of the script to check. Default 'enqueued'.
 531   *                       Accepts 'enqueued', 'registered', 'queue', 'to_do', and 'done'.
 532   * @return bool Whether the script is queued.
 533   */
 534  function wp_script_is( $handle, $status = 'enqueued' ) {
 535      _wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle );
 536  
 537      return (bool) wp_scripts()->query( $handle, $status );
 538  }
 539  
 540  /**
 541   * Adds metadata to a script.
 542   *
 543   * Works only if the script has already been registered.
 544   *
 545   * Possible values for $key and $value:
 546   * 'strategy' string 'defer' or 'async'.
 547   *
 548   * @since 4.2.0
 549   * @since 6.9.0 Updated possible values to remove reference to 'conditional' and add 'strategy'.
 550   *
 551   * @see WP_Dependencies::add_data()
 552   *
 553   * @param string $handle Name of the script.
 554   * @param string $key    Name of data point for which we're storing a value.
 555   * @param mixed  $value  String containing the data to be added.
 556   * @return bool True on success, false on failure.
 557   */
 558  function wp_script_add_data( $handle, $key, $value ) {
 559      return wp_scripts()->add_data( $handle, $key, $value );
 560  }


Generated : Sat Nov 28 08:20:01 2026 Cross-referenced by PHPXref