钩子文档

wp_default_scripts

💡 云策文档标注

概述

wp_default_scripts 是一个 WordPress 动作钩子,在 WP_Scripts 实例初始化时触发,允许开发者在脚本系统初始化时添加自定义脚本。

关键要点

  • 触发时机:当 WP_Scripts 实例初始化时触发。
  • 参数:传递 WP_Scripts 实例的引用,便于直接操作脚本对象。
  • 用途:主要用于在脚本系统初始化阶段添加自定义脚本,以便后续通过 wp_enqueue_script 或 admin_enqueue_script 调用。
  • 版本历史:自 WordPress 2.6.0 版本引入。

代码示例

add_action('wp_default_scripts', function(&$scripts) {
  // 参数顺序:$scripts->add( 'handle', 'url', 'dependencies', 'version', 'in_footer' );
  // 设置 "in_footer" 参数为 1 以在页脚输出脚本。
  $scripts->add('my-plugin-script', '/path/to/my-plugin-script.js', array('jquery'), 'alpha', 1);
});

注意事项

  • 确保在钩子中使用相同的 "handle" 字符串,建议为句柄名称添加插件或主题前缀以避免冲突。
  • 添加脚本后,可在主题或其他插件中通过 wp_enqueue_script 引用,例如依赖自定义脚本。

📄 原文内容

Fires when the WP_Scripts instance is initialized.

Parameters

$wp_scriptsWP_Scripts
WP_Scripts instance (passed by reference).

Source

do_action_ref_array( 'wp_default_scripts', array( &$this ) );

Changelog

Version Description
2.6.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Add a script where you can refer to from anywhere in your WordPress installation using wp_enqueue_script or admin_enqueue_script.

    First setup the hook, for example in your plugin.

    add_action('wp_default_scripts', function(&$scripts) {
      // Arguments order: `$scripts->add( 'handle', 'url', 'dependencies', 'version', 'in_footer' );`
      // Set "in_footer" argument to 1 to output the script in the footer.
      $scripts->add('my-plugin-script', '/path/to/my-plugin-script.js', array('jquery'), 'alpha', 1);
    });

    Now you can use the script from the plugin anywhere for example in your theme.

    add_action('wp_enqueue_scripts', function () {
      wp_enqueue_script('my-theme-script', '/path/to/my-plugin-script.js', array('my-plugin-script'), null, true);
    });

    Please make sure that you pick an identical string for the “handle” argument, a good practice is prefixing the handle name with your plugin or theme name.