While working on my upcoming WordPress theme, RedTwo (slated to be released soon), I realized that in order to properly set up the theme as I had envisioned with a fully fleshed out options panel, I was first going to have to 1) decide on an options panel to use, and 2) find a solution to drop customized CSS rules in based on some of the built-in options.

For options, I decided upon Devin Price’s modest Options Framework to keep things clean and because I am familiar with it from previous projects. But whatever you choose shouldn’t really matter all too much besides outputting your options as your framework requires.

As for the little CSS dilemma and ample research into what other premium theme authors suggest doing in cases like this, I was feeling a bit underwhelmed about just dropping the appropriate PHP rules into a style tag in the WordPress header.php file. While certainly the easiest solution for the problem, standards compliant, and generally still acceptable, it wasn’t what I was hoping for here. Thus I set out to seek more information on dynamic, custom field and/or custom option-based CSS rules and began my journey. The issue of course being that any PHP logic dropped into a standard CSS file just wouldn’t work. You could certainly call it into the functions.php file and include it everywhere, but that seemed like an weird place for a moderately sizable chunk of CSS to live as well. On its own was the ideal scenario.

The solution I came across and put into place ended up being as follows.

Stylesheet with Theme Option Calls – style-options.php

Create a new file, style-options.php in your theme’s root directory and drop in your custom style rules using normal CSS setup; the twist of course is being able to output options as chosen in Theme Options panel. Make sure you use the correct PHP call to get an option based on the framework you’re using — in this case I’m echoing my options using of_get_option().

.some-element { 
    position: <?php echo of_get_option('some-element-position'); ?>; 
}
.another-element { 
    color: <?php echo of_get_option('another-element-color'); ?>; 
}

Parse Dynamic Options Stylesheet – functions.php

Add this code to your existing functions.php file. This function will look for your style-options.php file and set a header telling it to be parsed as a CSS document rather than PHP.

if( !function_exists( 'style_options' ) ) {
	function style_options( $wp ) {
	    if( !empty( $_GET['theme-options'] ) && $_GET['theme-options'] == 'css' ) {
        	# get theme options
        	header('Content-Type: text/css');
        	require dirname(__FILE__) . '/style-options.php';

        	exit;
            }
	}
	add_action( 'parse_request', 'style_options' );
}

That’s all, folks!

One thought on “Dynamic Stylesheets with WordPress & PHP

Leave a Reply

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

Continue Reading