Create Dynamic CSS With PHP – Use CSS To Power Your WordPress Theme

In the previous part of this series I went over the basics of the PHP_CSS class that I created. I showed how it is a much more uniform and easy way to create your custom css with PHP than any other way.

In this part, I’ll be showing you how to use css to power your WordPress theme.

This will be an advanced tutorial, so if you’re just getting started with WordPress, PHP, or CSS then this might not be for you, but either way if you follow along you should be just fine.

Since we’re working with WordPress there are many ways we can go about creating our css and integrating it into our theme. In this part we’ll focus on the quickest way to get set up. Let’s begin!

Integrate The CSS Into Your Theme

We need to import the PHP_CSS class by including it into your theme’s folder structure, and then requiring the framework.

require_once( get_template_directory_uri() . '/includes/class-php-css.php' );

Now here comes the fun part. Once you’ve imported the class and set it up you can begin adding css via filters. Let’s start by creating two actions.

The first action will add the css to the header, and instantiate our PHP_CSS class to be used within our second hook. We’ll also add the css to the head of the document if our css is not empty.

add_action( 'wp_head', 'add_theme_header_styles' );
function add_theme_header_styles()
	// Instantiate the PHP_CSS object
	$css = new CarlosRios\PHP_CSS;

	 * theme_header_css hook
	 * Allows you to add css from different areas without having to
	 * instantiate a new instance of the PHP CSS Class every time
	 * @since  1.0
	 * @param  $css Instance of CarlosRios\PHP_CSS
	do_action( 'theme_header_css', $css );

	// Store the output as a string
	$output = $css->css_output();

	// Check if the output has data, and output it if it does
	if( !empty( $output ) && $output !== '' ) {
		echo '<style>' . $output . '</style>';

The second action will be where we actually add our css. This hook would be available for any plugin or theme requirement which would want to add css to our header. It comes with one argument, with is the instance of the PHP_CSS class stored in the $css variable.

add_action( 'theme_header_css', 'add_body_styles' );
function add_body_styles( $css )
	// Set the css for the body
	$css->set_selector( 'body' );
	$css->add_properties( array(
		'background'	=> '#222',
		'color'		=> '#FFF',
	) );

	return $css;

Now that we’ve got that setup our theme should contain the css that we added in the theme_header_css hook.

Create An Advanced CSS Process

While the method described in this tutorial will certainly get the job done, it’s not actually the best way to do so. Stay tuned for the next part in the series where I’ll show you how to create all of our css via a hook, add that css to a dedicated css file, and then enqueue that file automatically.