您有几种方法可以使用数据库值:
a) 将它们作为内联样式回显
<body style="background:<?php echo get_option('body_background'); ?>">
b) 在<head> 标签内将它们作为样式规则回显:
<head>
<style>
body {background:<?php echo get_option('body_background'); ?>}
</style>
</head>
C) 使用 PHP 生成动态样式表(这是最好的,因为文件可以被缓存,可能还有compressed):
style.php:
<?php
header("Content-type: text/css; charset: UTF-8");
define('WP_USE_THEMES', false);
require('path/to/wp-load.php'); // Located in the root of WordPress
?>
body {background:<?php echo get_option('body_background'); ?>}
header.php:
<head>
<link href="style.php" rel="stylesheet" type="text/css" />
</head>
编辑(2016 年 3 月)
我最终创建了wp-dynamic-css:一个允许您从动态内容生成 CSS 的库,我相信这对您非常有用。可以这样使用:
// 1. Load the library
require_once 'wp-dynamic-css/bootstrap.php';
// 2. Set the callback function (used to convert variables to actual values)
function my_dynamic_css_callback( $var_name )
{
return get_theme_mod($var_name);
}
wp_dynamic_css_set_callback( 'my_dynamic_css_callback' );
// 3. Enqueue the stylesheet (using an absolute path, not URL)
wp_dynamic_css_enqueue( 'path/to/my-style.css' );
现在假设您有一个名为 my-style.css 的文件,其中包含以下代码:
body {
background-color: $body_bg_color;
}
例如,如果调用get_theme_mod('body_bg_color') 返回值#fff,那么my-style.css 将被编译为:
body {
background-color: #fff;
}
这将打印到文档<head>。这种方法的好处是,在定制器中所做的任何更改都会立即更新,以显示更改实时生效。