I have a wordpress theme which injects dynamically with php created css code into the html head section of my wordpress site.
The actual css-code is defined as a string variable with the different css-style information sequentially being appended to this variable. This whole thing is nested within a function which is loaded into the head section via the wp_head
hook looking like:
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' );
I'd rather have this dynamic css file loaded as extra stylesheet than having inline code inside my head section.
With help of two stackoverflow discussions regarding dynamic css([this][1] and [this][2]) I tried to alter the existing script so that I can load it as css stylesheet via wp_enqueue_style
hook in my functions.php
. The dynamic_css.php
looks as follows:
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();
and the hook in the functions.php
:
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');
Unfortunately this does not work and I don't know why. There's no error message and in the source.html the file is correctly listed.
<link rel='stylesheet' id='dynamic_style-css' href='...website_url.../dynamic_css.php?ver=...' type='text/css' media='all' />
However the css styling information is not loaded and applied to the site. To me it seems that the php file is not executed. I don't understand why concatinating the styling information to one variable and directly echoing this variable to the html head section works, but loading it as as stylesheet doesn't.
Thanks for any hint and help!
The [1]: Dynamic CSS with PHP [2]: How can I use php to generate css?