【问题标题】:Should This Be In Its Own Stylesheet, and How? (PHP In Stylesheet?)这应该在它自己的样式表中,以及如何? (样式表中的 PHP?)
【发布时间】:2025-12-13 17:10:01
【问题描述】:

构建一个 WordPress 选项面板。它所做的一件事是允许用户选择自定义颜色。我使用默认样式表,然后为自定义输入调用样式。但是,我只是将其插入到标题中,而不是让这些自定义值驻留在它们自己的样式表中(因为我需要通过 PHP 调用用户的选择)。

例如,我的标题中有这样的代码:

<style type="text/css">
p a { <?php echo get_option('to_custom_css'); ?> }
</style>

在我的功能中:

array( "name" => "Custom CSS",  
    "desc" => "Want to add any custom CSS code? Put in here, and the rest is taken care of. This overrides any other stylesheets. eg: a.button{color:green}",  
    "id" => $shortname."_custom_css",  
    "type" => "text",  
    "std" => ""),    

如何在仍然使用&lt;?php echo get_option('to_custom_css'); ?&gt; 调用用户输入的同时将其驻留在自己的样式表中?

【问题讨论】:

  • ...这是我一整天听到的最悲伤的消息。
  • 查看 daiscog 的回答,了解似乎是一种解决方法。
  • @LucasWynne 如果将样式表的扩展名设置为 .php,则可以。或者,如果您使用的是 Apache,您可以将任何特定文件设置为由 PHP 处理,甚至可以使用 mod_rewrite 将 some_file.css 的所有请求传递给 some_other_file.php。您只需要记住将 PHP 文件中的 Content-type 标头设置为“text/css”。
  • 您是否需要在主题或仪表板/管理中具有样式?

标签: php css wordpress header


【解决方案1】:

您可以在 PHP 中创建样式表,但需要将 Content-type 标头设置为 text/css。在您的 HTML 中:

<head>
  <link rel="stylesheet" type="text/css" href="user-styles.php" />
  <!-- ... -->

在user-styles.php中:

<?php

header('Content-type: text/css');

?>
/*  now put your css here : */

p a { 
    <?php echo get_option('to_custom_css'); ?> 
}

/* and so on... */

【讨论】:

    【解决方案2】:

    首先,将其添加到您的.htaccess 文件中,以便它能够解释在 css 文件中找到的 php:

    AddType application/x-httpd-php .css
    

    然后,链接到外部样式表。使链接动态包含确定用户的 css 值所需的信息(可能是 id 号),如下所示:

    <link rel="stylesheet" href="http://www.yourserver.com/customstyle.css?id=<?php echo $userid; ?>" type="text/css" />
    

    最后,将php代码放入动态打印出css的样式表中,如下所示:

    <?php echo get_option('to_custom_css'); ?>
    

    使用$_GET['parametername'] 检索允许您计算css数据的参数。

    【讨论】:

      【解决方案3】:

      最终,您应该将 CSS 写入可以从托管页面包含的文件中。这样它就可以被浏览器缓存。

      <link rel="stylesheet" type="text/css" href="user1024/style.css" />
      

      【讨论】:

      • 任何PHP文件都可以被浏览器缓存。只需设置相关的 HTTP 标头即可。