【问题标题】:Is there a way to mix CSS and PHP?有没有办法混合 CSS 和 PHP?
【发布时间】:2017-09-03 05:33:31
【问题描述】:

我正在开发一个 wordpress 主题,我想要一个自定义标题背景。我曾经使用 wordpress 提供的add_theme_support('custom-header); 功能,它可以工作,但不是我想要的方式。我想要一个背景图像而不是一个 img。我创建了一个名为 header_background_callout() 的函数,并添加了一个部分,设置和控制。该函数工作并输出用户通过 wordpress 中的自定义部分选择的背景 url。有没有办法我可以在css中做这样的事情? :background-image: url(<?php echo wp_get_attachment_url(<?php get_theme_mod()); ?>);

提前致谢。

【问题讨论】:

标签: php css


【解决方案1】:

试试这个。 echo " 背景-img = 'url('get_theme_mod()')' ";

【讨论】:

    【解决方案2】:

    您可以使用 wp_add_inline_style 为您的主题添加内联样式:

    <?php wp_add_inline_style( $handle, $data ); ?>
    

    其中 $data 是您要包含在主题中的 CSS。这样您就可以将您的 php 变量加载为您网站的 CSS。

    【讨论】:

      【解决方案3】:

      是的,不错。
      我把我的css文件变成了一个php文件,因此我可以按照你说的做

      background-image: url(<?php echo get_theme_mod(); ?>); // I suppose you need to echo the mod?
      

      在 HTML 中你可以像这样使用它;

      <Link rel="stylesheet" type="text/css" href="style.php">
      

      编辑您可能需要通过以下方式将 php 文件的标头更改为 css 文件:

      <?php header("content-type: text/css; charset: UTF-8"); ?>
      

      【讨论】:

      • 成功了!但是有没有办法可以使用 wp_enqueue_style() 而不是在 html 文件中链接它?非常感谢。
      • 是的,我忘记了函数之前的 echo 和 wp_get_attachment_url()。
      • 我不知道那是什么。但通常我会说你可以在那里回显你想要的任何文本。
      【解决方案4】:

      我发现了这种简单的方法,而且效果最好:

      在您的 Index.php 文件中添加:

      <?php 
      
             function bg_img_alt() {
               if(get_theme_mod('vibe_hero_background_setting') > 0) {
                 return wp_get_attachment_url(get_theme_mod('vibe_hero_background_setting'));
               }else{
                 return get_template_directory_uri() . '/img/bg.jpeg';
               }
             }
      ?>
      
              <style type="text/css">
      
             background: linear-gradient(rgba(0,0,0,.3),rgba(0,0,0,.3)), url(<?php echo bg_img_alt(); ?>);
             background-repeat: no-repeat;
             background-position: center;
             background-size: cover;
             background-attachment: fixed;
          </style>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-30
        • 1970-01-01
        • 2022-06-10
        • 1970-01-01
        • 2021-11-05
        • 2019-03-30
        相关资源
        最近更新 更多