Using PHP variables with CSS

Approach can be different but I find this an easy approach to use. Below example shows the use of PHP variables in CSS in a WordPress plugin.

First, create a php file: dynamic.php (say). There just put the css codes where css properties are passed via php variables:

<style>
<?php
$wss_color = get_option(‘ws_slider_settings’);

$caption_color = esc_attr($wss_color[‘caption-color’]);
$desc_color = esc_attr($wss_color[‘desc-color’]);
$shadow_color = esc_attr($wss_color[‘shadow-color’]);

if($wss_color[‘caption-color’]!==”){
?>
.wss-caption p{
color: <?php echo $desc_color ?>;
opacity: 1;
}
<?php
}

if($wss_color[‘desc-color’]!==”){
?>
.wss-caption a{
color: <?php echo $caption_color ?>;
opacity: 1;
}
<?php

}?>

</style>

After that, you need to include this file in your plugin. For this, you can hook the file as shown:

function wss_generate_dynamic_style(){
require_once( WS_BASE_PATH .’/assets/php/dynamic.php‘);
}
add_action(‘wp_head’,array($this,’wss_generate_dynamic_style’));

That’s all, I hope anyone who is confused on using php variables with CSS will find this easy as I did 🙂

Leave comment

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