如何使用“wp_style_add_data”将样式表正确排队到 Wordpress 页面模板


How to correctly enqueue stylesheets to Wordpress page templates using 'wp_style_add_data'?

我已经学会了如何使用wp_style_add_data为早期版本的Internet Explorer添加样式表 - 这是理想的,因为它只覆盖必要的CSS规则并从我的style.css中获取其余部分。

除了我的page.php之外,我还有第二个页面模板,我将其命名为full-page.php几乎相同,除了对标题的一些更改和其他一些小差异。

因为我的模板几乎相同,所以当我可以做一些类似于 wp_style_add_data 函数的事情来只重写我需要更改的样式表时,编写两个长样式表似乎有点过分了。

我尝试使用wp_style_add_data将页面模板的样式表排队。这实际上有效,并采用我添加到style.css的任何样式,前提是它们在full-page.css中还不是不同的样式。

这是我使用的代码:

if (is_page_template('page-templates/full-page.php'))  
    { wp_enqueue_style( 'theme_style', get_stylesheet_uri() );
      wp_enqueue_style( 'theme-full-page', get_stylesheet_directory_uri() . '/css/full-page.css', array( 'theme_style' ) ); 
      wp_style_add_data( 'theme-full-page' );
} 
else { wp_enqueue_style( 'theme_style', get_stylesheet_uri() );
wp_enqueue_style( 'theme_style_ie8', get_stylesheet_directory_uri() . '/css/ie8.css', array( 'theme_style' ) ); 
wp_style_add_data( 'theme_style_ie8', 'conditional', 'IE 8' );

但是,它也会出现以下错误消息。

Warning
: Missing argument 3 for wp_style_add_data(), called in /var/sites/l/lucieaverillphotography.co.uk/public_html/wp-content/themes/lucieaverillphotography/functions.php on line 31 and defined in
/var/sites/l/lucieaverillphotography.co.uk/public_html/wp-includes/functions.wp-styles.php
on line
223

我认为这是因为我已经删除了告诉它仅在用户在IE 8上查看网站时才生效的部分,但是我一直在研究我可以添加的内容,但一直无法找到答案。

任何帮助将不胜感激。

更新:––

我想我已经设法解决这个问题,因为它现在似乎正在工作——我在style.css中所做的任何更改都会影响其他样式表full-page.css,除非我在full-page.css中指定其他内容。

查看代码,这是正确/最好的写出它的方法吗?这似乎有点长,我必须重复样式表名称很多,但它似乎也有效。我知道使用 PHP 通常有不同的做事方式,我担心以后在构建主题时会造成并发症。

if (is_page_template('page-templates/full-page.php'))

{ wp_enqueue_style( 'theme_style', get_stylesheet_uri() );
  wp_enqueue_style( 'theme-full-page', get_stylesheet_directory_uri() . '/css/full-page.css', array( 'theme_style' ) ); 
  wp_style_add_data( 'theme-full-page', 'title', 'theme-full-page' );
} 

您已经将样式排队,wp_style_add_data() 不会排队,它会将元数据添加到已经排队的样式中,并且此函数不允许空参数。 见下文。

if (is_page_template('page-templates/full-page.php')) { 
      wp_enqueue_style( 'lucieaverillphotography_style', get_stylesheet_uri() );
      wp_enqueue_style( 'lucieaverillphotography-full-page', get_stylesheet_directory_uri() . '/css/full-page.css', array( 'lucieaverillphotography_style' ) ); 
      //wp_style_add_data( 'lucieaverillphotography-full-page' );  --> not needed & cannot be used without required inputs
} 

但。。。。。您可以将所有 CSS 合并到一个文件中,并在所有页面上将其称为默认值(如果需要,可以调用 IE8 特定的样式表....),这样它可以被浏览器缓存,并且在第一次访问后,您的 CSS 加载速度更快......复习 CSS 特异性和 ids/类,从长远来看,它将为您节省大量工作!

如果你想对css进行特定于模板的更改,你有几个选择

  1. 如果 CSS 更改在文章/页面中,通常会有一个该页面唯一的 ID/类集(或自己添加一个)。

  2. 将自定义CSS直接添加到模板中(它适用于页面中的任何位置,不会受到标准的欢迎,但目前您可以将CSS规则放在样式标签内的任何位置

  3. 在 body 标签的标头中添加一个自定义类,例如>

然后,您可以在模板中专门针对 css...例如

 .page-id-2 header{ display: none;} //-->use chrome inspector to see what classes are outputted on each template