WordPress Theme Developers Tip – Call Dynamic CSS the Right Way

This solution should no longer be used. After further research and reading other’s suggestions, the ideal solution is to just output the css directly to the head section of your code.
While developing my Techozoic theme, I’ve progressed from adding custom CSS into the head section, to having an external file and using $_GET variables to pull options from the database, to now I believe is the right way to do it, using add_filter and a custom query in WordPress. By using this new method I’ve done away with unsafe $_GET variables and can now use any builtin WP functions in the external file.
First you’ll need to edit your functions.php file and add this block of code.

	add_filter('query_vars', 'add_new_var_to_wp');
	function add_new_var_to_wp($public_query_vars) {
		$public_query_vars[] = 'my_theme_custom_var';
		//my_theme_custom_var is the name of the custom query variable that is created and how you reference it in the call to the file
		return $public_query_vars;
	}

This sets up WP to now accept a new variable in a query called my_theme_custom_var the format of the query would be http://www.yourblog.com/index.php?my_theme_custom_var=css . The ? mark tells WP that this is a query and the = sign tells what the query variable should be set to.

Now to actually setup the function that will call the external file. I found this gem when looking at how popular WP theme called Atahualpa handled it’s external CSS.

	add_action('template_redirect', 'my_theme_css_display');
	function my_theme_css_display(){
		$css = get_query_var('my_theme_custom_var');
		if ($css == 'css'){
			include_once (TEMPLATEPATH . '/style.php');
			exit;  //This stops WP from loading any further
		}
	}

This code now will check if a query is passed to WP with the value my_theme_custom_var and if it is and has the value of css then it includes the style.php file which is our dynamic CSS file. Then the code exits which stops any other functions from happening other wise the whole home page is outputted along with the style.php file, which isn’t what is needed only the file.
Now you can use any WP functions on the style.php file as it is included from the functions.php file which is a standard WP file.
Source : Will Norris

About Jeremy Clark

Small town IT worker with interests in all things technological and technical. Biggest interests are in web development especially the WordPress publishing platform and the community supporting it. Currently developing and maintain the free WordPress theme Techozoic. I'm also always available for hire.
This entry was posted in guides, tech, wordpress and tagged , , . Bookmark the permalink.

20 Responses to "WordPress Theme Developers Tip – Call Dynamic CSS the Right Way"

Leave a reply

Comments will be sent to the moderation queue.