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:

https://gist.github.com/bappi-d-great/208d06bc3139f2076074

Hope it helps! :)

Leave a Reply

Your email address will not be published. Required fields are marked *