创建一个Wordpress主题时,有时需要增加额外的css和javascript文件,需要注意的是wordpress除了使用你写的主题外,还会使用其他插件,所以为了兼容性和各个插件和谐共处,需要使用wordpress的方式去引入css和js文件。
基本方法
在functions.php中使用wp_enqueue_script(), wp_enqueue_style()或者 wp_enqueue_block_style来加载js或css文件
加载css文件
首先style.css是每个主题文件都需要的样式文件,我们通常不在header.php中直接引入css文件,相反我们可以在functions.php中使用wp_enqueue_style()函数,比如要加载style.css,我们这样写:
wp_enqueue_style( 'style', get_stylesheet_uri() );
这个代码会查找叫style名字的css文件,然后加载它。
加载javascript文件
如果要加载js文件,也是类似方法,比如加载script.js
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js');
评论区回复脚本
通常情况下,classic主题如果使用评论功能,都需要加载评论回复脚本(block主题会自动加入)。比较合适的方式是先检查是否需要加载脚本,比如:
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
整合css及js加载
最后,为了更好的组织代码,我们把css和js的加载代码统一到一个函数里,如下:
function add_theme_scripts() {
wp_enqueue_style( 'style', get_stylesheet_uri() );
wp_enqueue_style( 'slider', get_template_directory_uri() . '/css/slider.css', array(), '1.1', 'all' );
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array( 'jquery' ), 1.1, true );
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );