dynamic css in 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.


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.


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


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



.box {

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


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




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' );



/*end of dynamic css*/