wp_register_style与wp_register_script的句柄需跨函数唯一吗?
关于WordPress中wp_register_style与wp_register_script句柄唯一性的问题
句柄必须全局唯一,不能在
wp_register_style和wp_register_script之间重复使用。WordPress内部用同一个全局存储体系管理所有注册的样式与脚本资源,重复的句柄会导致资源注册记录冲突,后续调用wp_enqueue_style或wp_enqueue_script时,可能无法正确加载对应资源,甚至引发程序错误。你提供的代码存在两个问题:
- 语法错误:
wp_register_script函数的参数之间缺失逗号,正确写法应该是:wp_register_script( 'bootstrap-twitter', 'https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js', array( 'jquery' ), '5.1.3'); - 句柄冲突:即便修正语法错误,用同一个
bootstrap-twitter句柄同时注册样式和脚本,会导致WordPress无法区分该句柄对应的是样式还是脚本,最终出现资源加载失败的情况。
- 语法错误:
正确的做法是给样式和脚本分配不同的唯一句柄,比如:
wp_register_style( 'bootstrap-css', 'https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css', array(), '5.1.3'); wp_register_script( 'bootstrap-js', 'https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js', array( 'jquery' ), '5.1.3'); wp_enqueue_style( 'bootstrap-css' ); wp_enqueue_script( 'bootstrap-js' );
内容的提问来源于stack exchange,提问作者Michael D
相关产品推荐
相关产品推荐

