WordPress stylesheet with dynamic value

Passing some dynamic values to the stylesheet of WordPress using PHP, might be a great way to utilize custom values to the styling of any WP theme. Sometimes it becomes obvious to take certain inputs from the WordPress user like changing theme background , colors of certain portions etc. It is easier for a Theme Developer to do that without even interacting with the theme options from any option panel or the core Theme customizers but for a regular non-tech one, it’s just a big challenge. So, we need to do it in a trickier way (We mean- the theme dev 😉 ) so that the end user find it easier.

OK, to do that Professional WP Theme developer takes the help of PHP, thank God WP runs with it. To do so we just have to rename our stylesheet file as if it was  a PHP file. Like, style.css should be style.php. But I don’t prefer changing the style.css file into a style.php as WP needs style.css to be defined in order to run a theme!  I do it in my themes as dynamic_style.php . So simple.

So the structure would be,

Now I would like you to always follow the best practice. Enqueue the file in the functions.php as a stylesheet. If you are not familiar with enqueue, how it works, just follow this link in the codex.

Here is a dummy function to do so,

In my case, the file is inside a CSS directory which is obviously inside the theme directory. (Theme name is Trone – under construction at this moment)

Ok, this part is done, now inside in your  “dynamic_style.php”, put the following lines of code:

Breaking down the code for your understanding:

The first line tells WP not to run theme related processes and the second line runs the WordPress engine. After this point, you have access to the WordPress functions and the global variables. The third line is to send header information as if this file is a text file of CSS.

Then just bring the dynamic code on! I am not explaining the following code which is a theme specific requirement for me. But I guess you can easily understand the scope of it.

Hope you have understood and now can add dynamic values to your WordPress stylesheet.  Let me know if you know  a better way to do so. Or can ask me question if you have any problem doing so.

 

Tag: WordPress stylesheet dynamic value

Author: Mizanur Rahaman Mizan

Mizanur Rahaman Mizan is an entrepreneur, blogger, innovator, life-long student of technology, marketing and sales, and in most occasion – a teacher of these subjects. By profession, he is dedicated to assisting businesses in achieving growth through new initiatives and the design and execution of innovative marketing and business development programs.

4 thoughts on “WordPress stylesheet with dynamic value”

  1. Awesome article. Will help us to use the stylesheets dynamically for the wp projects. Another magic of WordPress 😀.

Leave a Reply

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