使用css中wordpress主题选项的值

bud*_*ddy 1 css php wordpress wordpress-theming

我想用主题选项设置我的wordpress-theme的造型颜色.我的问题是,如何将主题选项的颜色值添加到我的CSS中?我知道主题选项值的存储位置,但是如何将其与我的CSS连接?

nic*_*ass 6

  1. 每次主题选项更改时使用PHP编写CSS文件(CSS缓存).

    您还可以利用像Less或Sass 这样的CSS预处理器,它们可以为您编译CSS.

    示例代码,假设您使用的是WP选项API:

    $theme_options = get_option('my_theme_options');
    
    // previous hash
    $oldHash = get_transient('my_theme_options_hash');
    
    // hash representation of your current theme options
    $currentHash = md5(var_export($theme_options, true));
    
    // compare hashes and regenerate if necessary
    if($oldHash !== $currentHash){
    
      // compile/write your CSS to a file here
    
      // update hash and make it expire after 14 days
      set_transient('my_theme_options_hash', $currentHash, 60 * 60 * 24 * 14);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在主题标题中放入内联CSS代码:

    <style>
      <![CDATA[]]>
       body{ 
         background-color: <?= get_option('my_theme_color'); ?>; 
       }
      ]]>
    </style>
    
    Run Code Online (Sandbox Code Playgroud)
  3. (最糟糕的选择)将样式表转换为输出的PHP脚本text/css.这很糟糕,因为你强迫你的服务器为每个用户页面请求运行两次WordPress.您可以调用仅加载基本WP组件的脚本,但它仍然比使用静态CSS慢