wordpress

How to use PHP inside CSS files in WordPress?

PHP is a server-side language and CSS is for styling purposes. They do not interact with each other. You can output CSS in a PHP file. For that, you can put PHP script inside <head> tag. Which looks as in the following.

<PHP> echo '<link rel="stylesheet" type="text/css" href="style.css"></head>'; <PHP>

But What if you have to write PHP code inside a CSS file. This situation comes when you want a dynamic value to put in CSS.

In WordPress, I got the same problem while I was doing a project.

MY PROBLEM

In a div with a class (say box) I need its background to be dynamic. Dynamic in the sense that the images should change with the change of server. The link should pick the image of the location from the Theme’s root. Theme root should be dynamic in CSS.

SOLUTION

The problem can be solved in the following ways.

1. Make custom.css.php file

In the CSS folder of your theme file make a new file named “custom.css.php”. and paste the code as below

<?php

 header("Content-type: text/css; charset: UTF-8");

$clr="#134e9c";

?>

.box {

background-image: url("<?php echo get_bloginfo('template_directory');?>/images/apple.jpg");

}

2. Then in functions.php add the following code.

/****************************************

DYNAMIC CSS

********************************************/
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', '', 1.5);

}

add_action('wp_ajax_dynamic_css', 'dynamic_css');

add_action('wp_ajax_nopriv_dynamic_css', 'dynamic_css');

function dynamic_css() {

  require( get_template_directory().'/css/custom.css.php' );

  exit;

}

/*end of dynamic css*/

 

jaminrai

Recent Posts

Skype Closes Its Doors After 20 Years: A Look Back and the Apps That Faded with It

After 20 years of transforming global communication, Skype has officially ceased operations. Microsoft, which purchased…

2 months ago

The Duck and the Tortoise: A Tale of Patience and Teamwork

In a serene forest by the edge of a sparkling lake, there lived a cheerful…

3 months ago

10 Smart Strategies for a Secure and Enjoyable Retirement

Retiring comfortably is a goal many aspire to achieve, and with the right strategies, it’s…

3 months ago

Troubleshooting a Slow Computer

Is your computer running frustratingly slow? Don't worry; you're not alone in facing this common…

3 months ago

The Clever Fox and the Greedy Crow

Once, in a sunny forest, Fox and Crow were friends. One day, Crow found a…

3 months ago