我有一个 wordpress 主题,它使用 php 创建的 css 代码动态注入到我的 wordpress 网站的 html head 部分。
实际的 css 代码被定义为一个字符串变量,不同的 css 样式信息依次附加到这个变量。这整个东西嵌套在一个函数中,该函数通过
wp_head
钩子加载到头部部分,如下所示:
function dynamic_css() {
$header_options = get_option( 'header_opt' );
/*... more code here ...*/
$css = '<style>';
$css .= '.logo {
max-width:'. $header_options['logo_width'] .'px;
}';
$css .= '.header-center > .center-max-width {
height:'. $header_options['center_height'] .'px;
}';
/*... more code here ...*/
$css .= '</style>';
echo '' . $css;
}
add_action( 'wp_head', 'dynamic_css' );
我宁愿将这个动态 css 文件作为额外的样式表加载,也不愿在我的 head 部分中包含内联代码。 在关于动态 css([this][1] 和 [this][2])的两个 stackoverflow 讨论的帮助下,我尝试更改现有脚本,以便我可以通过我的
wp_enqueue_style
挂钩将其加载为 css 样式表. functions.php
看起来如下:dynamic_css.php
和
header("Content-type: text/css; charset: UTF-8");
function dynamic_css() {
$header_options = get_option( 'header_opt' );
/*... more code here ...*/
$css = '.logo {
max-width:'. $header_options['logo_width'] .'px;
}';
$css .= '.header-center > .center-max-width {
height:'. $header_options['center_height'] .'px;
}';
/*... more code here ...*/
echo $css;
}
dynamic_css();
中的钩子:
functions.php
不幸的是,这不起作用,我不知道为什么。没有错误消息,并且在 source.html 中正确列出了文件。
function my_theme_enqueue_styles() {
wp_enqueue_style( 'dynamic_style', get_stylesheet_directory_uri() . '/dynamic_css.php');
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_styles');
然而,CSS 样式信息未加载并应用于网站。对我来说,似乎没有执行 php 文件。我不明白为什么将样式信息连接到一个变量并直接将此变量回显到 html head 部分有效,但将其作为样式表加载却不行。
感谢任何提示和帮助!
的 [1]:
使用 PHP 的动态 CSS[2]: 如何使用php生成css?