如何仅将自定义 css 样式应用于 Amp 页面

How do I apply custom css styles only to Amp pages

我有一个 wordpress 网站,我正在转换为 AMP 网站,现在我正在使用 amp plugin 现在我的网站有很多 css 文件,我可以内联的样式有限,所以我尝试使用 :

添加自定义 css
<style amp-custom>
 .someclass={/*my custom css I want it to affect only amp pages*/}

</style>

我可以通过将样式添加到 header.php 文件来毫无问题地将样式添加到所有页面,现在问题是我希望此样式仅应用于我的 amp 页面,它们有一个特殊的 urls (在末尾添加 ?amp)。

我可以让自定义 css 仅应用于 amp 页面吗?

有点棘手,但在论坛中搜索后,我发现 amp 插件 provides a method is_amp_endpoint() 用于了解页面是否为 Amp 页面,因此在 Wordpress 主题中有一点 PHP header.file 我们可以影响所有的 AMP 页面。

<style amp-custom>
<?php
    if (is_amp_endpoint()){
        echo(".mypanel_class{color:white !important;}");
        echo("div#myid{display:none;}");
    }
    ?>
</style>   

如果您使用 this 插件,则可以使用 amp_post_template_css 操作。

function custom_post_template_css() {
  ?>
  .someclass={
    /*my custom css I want it to affect only amp pages*/
  }
  <?php
}
add_action( 'amp_post_template_css','custom_post_template_css', 11 );

请参阅Custom CSS文档。