WordPress教程

新版WordPress需使用wp_enqueue_script管理js与css

阿里云

前几天在建英文站的时候遇到 WordPress 报告了一个警告,load_scripts 报告的,具体记不住了。引起这个警告的原因是主题插件未使用官方推荐的方式加载 js 与 css,比如直接在 wp_head 与 wp_footer 中输出 js 与 css 地址。正确的加载方式如下,取自 DUX 主题。

  1. add_action('wp_enqueue_scripts', '_load_scripts');
  2. function _load_scripts() {
  3. if (!is_admin()) {
  4.  
  5. $purl = get_stylesheet_directory_uri();
  6.  
  7. // common css
  8. _cssloader(array( 'app' => 'app'));
  9.  
  10. _jsloader(array('loader'=>'loader'));
  11.  
  12.  
  13. }
  14. }
  15. function _cssloader($arr) {
  16. 	foreach ($arr as $key => $item) {
  17. 		$href = $item;
  18. 		if (strstr($href, '//') === false) {
  19. 			$href = get_stylesheet_directory_uri() . '/css/' . $item . '.css';
  20. 		}
  21. 		wp_enqueue_style('_' . $key, $href, array(), THEME_VERSION, 'all');
  22. 	}
  23. }
  24. function _jsloader($arr) {
  25. 	foreach ($arr as $item) {
  26. 		wp_enqueue_script('_' . $item, get_stylesheet_directory_uri() . '/js/' . $item . '.js', array(), THEME_VERSION, true);
  27. 	}
  28. }
也想出现在这里?联系我们
创客主机

通过 _cssloader 函数加载 css,需提供以 css 文件名为键值的数组, _jsloader 函数加载 js,使用方法与 _cssloader 相同。最后通过 wp_enqueue_scripts 钩子挂载函数进行加载,通过这种方式加载 js 与 css,wordpress 就不会再提示警告信息了。

新版 WordPress 需使用 wp_enqueue_script 管理 js 与 css

已有 196 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!