我尝试做一些 self 研究并发现了这些问题 1和 2但它们都没有真正解决我的问题,所以我创建了一个新问题。
我尝试使用 wp_enqueue_scripts
函数将特定的 CSS 文件加载到特定的页面,但不知何故它总是跳过条件并继续到 else 条件。这是我的代码;
function theme_script_enqueue() {
if(is_page_template('index.php')) {
wp_enqueue_style('indexstyle', get_template_directory_uri() . '/css/news.css', array(), '1.0.0', 'all');
wp_enqueue_script('indexjs', get_template_directory_uri() . '/js/main.js', array(), '1.0.0', true);
} else {
wp_enqueue_style('mainstyle', get_template_directory_uri() . '/css/main.css', array(), '1.0.0', 'all');
wp_enqueue_script('mainjs', get_template_directory_uri() . '/js/main.js', array(), '1.0.0', true);
}
}
add_action('wp_enqueue_scripts', 'theme_script_enqueue');
当我访问 http://localhost:8888/wordpress/index.php
只是为了确保根据条件,我希望脚本加载 news.css
但它加载了 main.css
它们有一些不同颜色的元素所以我立即发现了。我确实在条件之间切换了 CSS 文件,当我尝试访问 index.php
时,它总是加载 else 条件。我做错了什么吗?
最佳答案
如此处所述:https://developer.wordpress.org/themes/template-files-section/page-template-files/
index.php — If no specific page templates are assigned or found, WordPress defaults back to using the theme’s index file to render pages.
所以根据我的理解,index.php 是后备而非模板。 您还必须描述您的模板文件:
<?php /* Template Name: Example Template */ ?>
你有没有把评论写到你的模板文件中?
关于php - WordPress 自定义页面 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53124268/