WordPress 加载 Javascript 和 CSS 的方法
有两种常用的 add_action 钩子可以加载 脚本和CSS到WordPress:
init: 确保始终为您的网站头部加载脚本和CSS(如果使用home.php,index.php或一个模板文件),以及其他“前端”文章、页面和模板样式。
wp_enqueue_scripts:“适当”的钩子方法,并不总是有效的,根据你的WordPress设置。
加载外部 jQuery 库和主题自定义的脚本、样式
下面这个例子在 add_action 钩子中使用 init。使用 init 有两个原因,一是因为我们正在注销WordPress默认的jQuery库,然后加载谷歌的jQuery库;二是确保在WordPress的头部就加载脚本和CSS。
使用if ( !is_admin() )是为了确保这些脚本和css只在前端加载,不会再后台管理界面加载。
1 2 3 4 5 6 7 8 9 10 11 12 13 | /** Google jQuery Library, Custom jQuery and CSS Files */ function myScripts() { wp_register_script( 'google', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js' ); wp_register_script( 'default', get_template_directory_uri() . '/jquery.js' ); wp_register_style( 'default', get_template_directory_uri() . '/style.css' ); if ( !is_admin() ) { /** Load Scripts and Style on Website Only */ wp_deregister_script( 'jquery' ); wp_enqueue_script( 'google' ); wp_enqueue_script( 'default' ); wp_enqueue_style( 'default' ); } } add_action( 'init', 'myScripts' ); |
加载WP默认 jQuery 库和主题自定义的脚本、样式
第3行:使用 array(‘jquery’) 是为了告诉 WordPress 这个 jquery.js 是依赖WordPress 的jQuery库文件,从而使 jquery.js 在WordPress jQuery库文件后加载。
1 2 3 4 5 6 7 8 9 10 | /** Add Custom jQuery and CSS files to a Theme */ function myScripts() { wp_register_script( 'default', get_template_directory_uri() . '/jquery.js', array('jquery'), '' ); wp_register_style( 'default', get_template_directory_uri() . '/style.css' ); if ( !is_admin() ) { /** Load Scripts and Style on Website Only */ wp_enqueue_script( 'default' ); wp_enqueue_style( 'default' ); } } add_action( 'init', 'myScripts' ); |
加载 print.css 到你的WordPress主题
第 3 行:最后的 ‘print’是媒体屏幕调用,确保 print.css 在网站的打印机中的文件加载时才加载。
1 2 3 4 5 6 7 8 | /** Adding a Print Stylesheet to a Theme */ function myPrintCss() { wp_register_style( 'print', get_template_directory_uri() . '/print.css', '', '', 'print' ); if ( !is_admin() ) { /** Load Scripts and Style on Website Only */ wp_enqueue_style( 'print' ); } } add_action( 'init', 'myPrintCss' ); |
如果你要在文章或页面加载唯一的脚本,那就应该使用 wp_enqueue_scripts 替换 init。使用 wp_enqueue_scripts 仅仅只会在前台加载脚本和CSS,不会在后台管理界面加载,所以没必要使用 !is_admin() 判断。
解决JS函数object is not a function的bug WordPress退出登录后跳转到指定页面的方法
还不错,顶一下