在WordPress中,JavaScript(JS)和CSS文件通常放在以下几个位置,具体取决于你的需求和项目结构:
你可以将JS和CSS文件放在当前使用的WordPress主题的文件夹中。通常,这些文件会放在以下子目录下:
wp-content/themes/your-theme-name/style.css
。wp-content/themes/your-theme-name/js
目录下。假设你的主题名为 my-theme
,你可以这样组织文件:
wp-content/
└── themes/
└── my-theme/
├── style.css
└── js/
└── main.js
wp_enqueue_scripts
钩子为了确保JS和CSS文件正确加载,你应该使用WordPress提供的 wp_enqueue_scripts
钩子来注册和加载这些文件。
在你的主题的 functions.php
文件中添加以下代码:
function my_theme_enqueue_scripts() {
// 加载CSS文件
wp_enqueue_style('my-theme-style', get_template_directory_uri() . '/style.css');
// 加载JS文件
wp_enqueue_script('my-theme-js', get_template_directory_uri() . '/js/main.js', array('jquery'), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');
如果你正在对现有主题进行修改,建议创建一个子主题,以避免直接修改父主题文件,从而在更新主题时保留你的更改。
wp-content/themes
目录下创建一个新的文件夹,例如 my-theme-child
。style.css
文件,并添加以下内容:/*
Theme Name: My Theme Child
Template: my-theme
*/
functions.php
文件,并添加以下代码:add_action('wp_enqueue_scripts', 'my_theme_child_enqueue_scripts');
function my_theme_child_enqueue_scripts() {
wp_enqueue_style('my-theme-child-style', get_stylesheet_uri());
wp_enqueue_script('my-theme-child-js', get_stylesheet_directory_uri() . '/js/main.js', array('jquery'), '1.0.0', true);
}
通过以上方法,你可以有效地管理和加载WordPress中的JS和CSS文件,确保网站的性能和可维护性。
领取专属 10元无门槛券
手把手带您无忧上云