php - WordPress 自定义页面 CSS

标签 php css wordpress

我尝试做一些 self 研究并发现了这些问题 12但它们都没有真正解决我的问题,所以我创建了一个新问题。

我尝试使用 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/

相关文章:

php - 使用 PDO 处理错误的最佳实践

php - 包含架构、域和端口的完整 url

javascript - 不同浏览器中奇怪的 jquery 动画行为

javascript - 将 html 标签作为文本输出到 div 中,每个数组元素在单独的行上

html - 增加输入占位符中 html 特殊字符 (·) 的大小

php - 如果数据库中不存在任何行,则为变量提供两个值

php - DooPHP 中的复杂 ORM

css - 媒体查询大小和定位字体

php - 在 WooCommerce 中为自定义字段使用 wc_get_orders() orderby 参数

html - <a> 在 header : only part of it works? 中