Dynamic css using php

CSS Variables Using PHP

CSS is an amazing formatting tool but it has one glaring omission: variables. In My CSS Wishlist, I proposed a PHP-like syntax for CSS variables. Using PHP, I’ve made the idea of easy, dynamic CSS a reality.

The Sample CSS

The above is a sample css file that we’ve named «default.css». For those that don’t know PHP, any string that begins with $ is a variable.

The PHP

/* get the stylesheet */ $stylesheet = @is_file($_GET['stylesheet']) && strtolower(substr(strrchr($file_name,'.'),1)) == 'css' ? $_GET['stylesheet'] : 'default.css'; /* set the header information */ //will be output as css header('Content-type: text/css'); //set an expiration date $days_to_cache = 10; header('Expires: '.gmdate('D, d M Y H:i:s',time() + (60 * 60 * 24 * $days_to_cache)).' GMT'); /* set the dynamic information */ //default css variable information $default = array( 'body_font_size' => '16px', 'body_text_color' => '#00f' ); //red css variable information $red = array( 'body_font_size' => '10px', 'body_text_color' => '#f00' ); /* extract the propery array's information */ extract($_GET['theme'] && $ ? $ : $default); /* load in the stylesheet */ $content = preg_replace('/\$([\w]+)/e','$0',@file_get_contents($stylesheet)); /* spit it out */ echo $content;

There’s a fair amount going on in the PHP above:

  1. We check to see if a specific stylesheet is has been asked for. If not, we’ll use a default stylesheet template. In this case, the default template is «default.css». We also check to make sure that the requested file is a «.css» file and that it file actually exists.
  2. We set the header information, including: the content type, which is «text/css», and an expiration date, which isn’t required but recommended for caching purposes.
  3. We set keys and values of the variables we will use in our stylesheet theme. These key => values are stored in arrays so that we may have different themes. Above we have a «default» theme and a «red» theme. Note the differences in font size and text color.
  4. We check to see if a specific theme has been asked for. If not, we use the $default theme. If the requested them doesn’t exist, we serve the default theme.
  5. We read in the file content and replace any string beginning with «$» with the value specified in the PHP file’s theme.
  6. We echo the output. Done.
Читайте также:  Elasticsearch python search example

The Usage

The Result

Voila! Variables are replaced by their values in the output. That’s it!

Источник

Dynamic CSS stylesheets with PHP.

In this tutorial, I will show you the basics of how to create a dynamic CSS stylesheet using PHP. In certain cases, you may want to dynamically display a color or style that is based on a value in your database or a configuration file. Example: The users of your website can select a background colour for their profile.

Let’s take a look at a simple example of a PHP file that outputs CSS:

  1. We set the content type to text/css. This tells the browser that the output should be interpreted as CSS. We also set the charset to UTF-8.
  2. We created two PHP variables: $backgroundColor, which contains the hex value for the color of our background, and $textColor, which contains the hex value of our text. For this example, I’ve used “#000000” (black) for the background and “#FFFFFF” (white) for the text color.
  3. We then output some CSS as normal, filling in the blanks with our PHP variables.

Here’s an example of a HTML page including a PHP stylesheet:

As you can see, we simply include the style.php file as if it was a CSS file. Note that you will have to change the extension of the file with mod_rewrite if you want the filename to contain a .css extension instead of a .php extension (if you are serious about implementing a dynamic stylesheet that is outputted by PHP, then this is probably the best course of action to take, as older browsers may not accept the .php extension).

If you run the example above, you will see that the webpage has a black background color and white text that reads “Hello world!”

Источник

Dynamically generate static CSS files using PHP

If you are a premium theme developer, there may be times when you will need to generate dynamic CSS/JavaScript files to be used inside your theme. An example to this is when you want the users to be able to change certain aspects of the CSS including colors, backgrounds, padding, borders, or add their own CSS classes/id’s.

Introduction

There are a few popular approaches that theme developers used, including directly inserting the CSS code inside header.php, or call it from a style.php file.

But these approaches have problems of its own. For example, inserting CSS directly skips the wp_enqueue_style and still adding a few PHP calls to the header every time the page loads; or using style.php would not only adding more PHP calls, but also require the server to load WordPress twice which is a no-no. Worse of all, none of these methods provide an ideal environment for cache plugins like W3 Total Cache. Ultimately, nothing beats the old school way which is a static CSS (e.g. styles.css) which is then enqueued inside functions.php – and that’s the direction I’m going with this tutorial.

The method

1. Create a styles.php file containing your CSS codes. Below is just an example.

/*---------------------- Body --------------------------*/ body < background:; color:; font-family: ; font-size: ; >

Notice that we have none of the bloated header(«Content-type: text/css»); or include ‘../../../../wp-load.php’; . Also, since I’m using the SMOF, my serialized options data can be called using $data[‘id’] . Yours might look a little different, for example get_option(‘my_body_color’) .

2. Create a function to generate the static CSS file using styles.php

We are going to create a function that generates a static CSS file, then place this file inside our theme folder. This function is written inside admin-functions.php of the SMOF.

function generate_options_css($newdata) < $data = $newdata; $css_dir = get_stylesheet_directory() . '/css/'; // Shorten code, save 1 call ob_start(); // Capture all output (output buffering) require($css_dir . 'styles.php'); // Generate CSS $css = ob_get_clean(); // Get generated CSS (output buffering) file_put_contents($css_dir . 'options.css', $css, LOCK_EX); // Save it >

Since that’s more than a few lines I’m going to explain them by bits.

  • $newdata is the input which the function will process. Here I am converting the variable to $data so that I can use it inside styles.php . More on that later.
  • $css_dir defines the folder of which your CSS file will be stored.
  • ob_start() , ob_get_clean() – these are the two magic functions that will capture whatever was called inside styles.php, and store them inside $css.
  • Finally, your newly generated css codes will be printed on a file called options.css using file_put_contents()

3. Using the function
This is the most important part. The rule of thumb is, the CSS file MUST ONLY be generated when the variables inside styles.php were changed. Otherwise, this defeats the purpose of taking the trouble of generating a static CSS file to minimize the number of PHP calls on page load. For this tutorial, I’m just going to explain how it is done inside SMOF. It should serve as a guide for usage in other areas e.g. plugins or shortcodes – I’d probably write another tutorial for that in the future.

I’m going to hook the function every time the user saves or resets the options, using this line of code:

generate_options_css($data); //generate static CSS file

This went into two areas inside admin-interface.php of the SMOF. The first area is when the ajax save action is called somewhere on line 710, after update_option(OPTIONS, $data); . The final code would look like this:

update_option(OPTIONS, $data); generate_options_css($data); //generate static CSS file

The second area is when the user resets the options, somewhere on line 35-37, after update_option(OPTIONS,$defaults); . The final code would look something like this:

$defaults = (array) $options_machine->Defaults; update_option(OPTIONS,$defaults); generate_options_css($defaults); //generate static css file

4. Register your static CSS file and enqueue it to your header.
From this point forward, everything else is pretty much straight forward. Here’s a little snippet of my functions.php file.

function themename_enqueue_css() < wp_register_style('options', get_template_directory_uri() . '/css/options.css', 'style'); wp_enqueue_style( 'options'); >add_action('wp_print_styles', 'themename_enqueue_css');

As a wrap up, this is the summary of this tutorial:

  • Create a function to generate a static CSS file
  • Call this function only when the options were changed
  • Register and enqueue your static CSS file in your themes’ functions.php file.
  • Minimize the number of PHP calls every time the page loads
  • Avoid using wp-load that loads WordPress twice.
  • Cleaner and standard-driven coding.

I hope you find this article useful and help you to spawn more creative ways to implement it inside your themes, plugins, shortcodes, and widgets. Note that this same trick can be used for other types of files including, yes, JavaScript!.

Источник

Оцените статью