How to write dynamic css in a php file in wordpress

It’s always standard to maintain a separate css file for styling, even for dynamic css that is generated by the theme options. Most of the theme developers include this dynamic styles into the header or footer using wp_head or wp_footer hook. How’s about having a totally separate css file for the dynamic styles? It’s pretty simple so let’s start!
In my example, I have used redux framework, so that I have a global variable. In my case, I assume my global variable is $lts. So, in functions.php you need to add like this:
[php]
// Adding custom script
add_action( ‘wp_enqueue_scripts’, ‘theme_custom_style_script’, 11 );
function theme_custom_style_script() {
wp_enqueue_style( ‘dynamic-css’, admin_url(‘admin-ajax.php’).’?action=dynamic_css’, â€, VERSION);
}
// Ajax handler for wordpress
add_action(‘wp_ajax_dynamic_css’, ‘dynamic_css’);
add_action(‘wp_ajax_nopriv_dynamic_css’, ‘dynamic_css’);
function dynamic_css() {
// Assuming the css file is in /wp-content/themes/THEME_NAME/assets/css/ directory
require( get_template_directory().’/assets/css/custom.css.php’ );
exit;
}
[/php]
Then in custom.css.php file add this:
[php]
body{
/* You can use your theme option variable here, just declare it as global variable first */
color: ;
}
[/php]
Gist code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!– functions.php –> | |
<?php | |
add_action( 'wp_enqueue_scripts', 'theme_custom_style_script', 11 ); | |
function theme_custom_style_script() { | |
wp_enqueue_style( 'dynamic-css', admin_url('admin-ajax.php').'?action=dynamic_css', '', VERSION); | |
} | |
add_action('wp_ajax_dynamic_css', 'dynamic_css'); | |
add_action('wp_ajax_nopriv_dynamic_css', 'dynamic_css'); | |
function dynamic_css() { | |
require( get_template_directory().'/assets/css/custom.css.php' ); | |
exit; | |
} | |
?> | |
<!– custm.css.php file –> | |
<?php | |
header( "Content-type: text/css; charset: UTF-8" ); | |
global $lts; | |
?> | |
body{ | |
color: <?php echo $lts['base-color'] ?>; | |
} |
Hope it helps!