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.

Create Dynamic CSS With PHP – The PHP CSS Class

Before we begin, I have to first be very clear that CSS for the most part should not be created exclusively with PHP. While you can certainly create all of your site’s CSS with PHP, it is neither efficient or wise to do.

CSS has developed into a vibrant language, especially with the recent rise of preprocessors such as SASS and LESS.

You should create most of your design in SASS or just raw CSS, and only leave PHP for the things that the user will be able to change on their own.

Understanding The PHP CSS Class

Lets begin the project by first downloading the PHP CSS Class which I built for this tutorial.

Download The CSS Class

The PHP CSS class is the best way to handle this because of the fact that once we’ve got information stored in the object it is then easy for us to manipulate that information over and over again. The class also provides us with methods that will allow us to do things uniformly and efficiently. Just remember that we’ll be writing CSS utilizing PHP, so it will look more like PHP. Let’s set it up.

require_once 'path_to_library/class-php-css.php';

use CarlosRios\PHP_CSS;

$css = new PHP_CSS;

Setting The HTML DOM Selector

The PHP CSS class allows us to easily set and change selectors so that at any given moment we’re working with one individual selector or set of selectors. We set the selector in the same way that we would in CSS like so.

$css->set_selector( '#content' ); // Sets #content as the selector to add properties to

$css->set_selector( '#content, #wrapper, body' ); // Sets multiple selectors

Changing The Selector

Once we’ve set the selector’s we can begin adding rules to them, but before we do that I’d like to point out that if you wish to change the selector once it’s been set you can use either the change_selector()  method or the set_selector()  method once again.

$css->change_selector( '#something-different' );

Adding CSS Properties To A Selector

Once we have a selector set we can begin adding properties to it. The properties are any valid css property paired with a value (which is where the PHP CSS class really shines). First let’s setup some variables and then re set the selector.

// Set some variables
$background_color_value = '#FFF';
$background_image_url = '';
$text_color_value = '#222';
$display_value = 'block';

// Set a selector
$css->set_selector( '#header' );

To add a single property we use the add_property()  method which requires two arguments. The first is the property-type and the second is the value.

// Add a single property
$css->add_property( 'background-color', $background_color_value );

To add multiple properties you can use the add_properties()  method which requires an array as its only argument.

// Add multiple properties at once
$css->add_properties( array(
	'color' => $text_color_value,
	'background-image' => $background_image_url,
	'display' => $display_value,
) );

Now that we’ve set multiple properties to the ‘#header’ selector, our css output would be as follows:


Handling Pseudo Class Properties

Adding properties to the pseudo classes or states of the selector comes builtin to the PHP CSS class. Once we add pseudo classes to the selector states the PHP CSS class will automatically store all of the rules created before and add new properties to the selector with the state added to it.

$css->set_selector( '#header' );
$css->add_selector_state( ':hover' );

Then we can continue adding properties.

$css->add_property( 'border-color', '#222' );

Which would output:

	border-color: #222;

Adding Multiple Pseudo Classes To A Selector

We can also add multiple pseudo classes to the selector by using the add_selector_states()  method which requires an array as its single argument. Using this method will create an output of the css selector for each state that you specify.

$css->set_selector( '#header' );
$css->add_selector_states( array( ':hover', ':active' ) );
$css->add_property( 'text-align', 'center' );

The output would then be as follows.

#header:hover, #header:active{
	text-align: center;

Removing Pseudo Classes

We could then revert the selector back to its original state without any pseudo classes by using the reset_selector_states()  method, and then continue adding to the original selector.


Outputting Our CSS

After we’ve created all of our css, we can use the PHP CSS class’ css_output() method to display all of the css that we’ve created. Please note that this class was not intended to generate a ton of css code, so as of now the PHP CSS class will only output minified css.

<style><?php echo $css->css_output(); ?></style> // Print the css onto the page

file_put_contents( 'style.css', $css->css_output() ); // Save the css to a separate file

Future Plans For Development

With all of that said, there isn’t much more that this class was created to do, but I will continue adding special rules to it as I need them. I would encourage you to fork the PHP CSS class on github, and send some pull requests my way so that I can continue adding to it. Otherwise stay tuned for the next tutorial where I’ll show you how you can integrate this class into your next WordPress theme or plugin.

Create Dynamic CSS With PHP – Introduction

In 2015 I began working on a project that was created for me to offer my clients a cheaper alternative to the custom development work that I do for them. The project consisted of creating a WordPress theme that was dynamic, up to date in terms of design, allowed almost complete customization, and was lightweight enough that SEO would not be affected by it.

I’ve worked with premium WordPress themes countless times, and I knew first hand that the way they achieve their large customization options isn’t always done with the best practices in mind for SEO, and certainly isn’t done with much consideration for the overall weight of the site.

As a WordPress developer and someone who my customers look to as an expert, I found it too risky to just purchase a theme and then resell that theme under the banner of my business.

Instead I spent a few months creating a lightweight multi-purpose theme that I’m successfully used on about 5 websites as of now (March 29, 2016).

That theme, while not publicly available is called ThemeOne, and is currently hosted in a private repo on my github account.

Create Dynamic CSS With PHP For Your WordPress Theme

Now to get back to the main point of this series of articles, the issue I ran into with ThemeOne was that every time I wanted to create some css that would change the layout, I would have to write css pretty much manually in PHP. On top of that, I was echoing CSS all over the page which is a bad enough practice as is.

Instead of writing CSS with PHP all over the place, and doing it differently every time, I decided that it would be best to create a class that would handle writing all of my custom CSS, write browser specific prefixes for properties that require them, and output a minified string that could be saved in a .css file or in the <head> of the document.

Over the next few articles I’ll go into greater depth about how I created the class, and then how I integrated it into my WordPress theme.

Until then you can view or fork my finished css class for php from my github page.

PHP CSS Library