2

I know there have been lots of discussions on here about rendering a css file with php variables. The "no no" way of bootstrapping the wp-load.php for example.

I've been working on a theme framework for a few months now and one of the things it does is generate a css file using the parse request action.

add_action( 'parse_request', 'parse_dynamic_css_request' );
function parse_dynamic_css_request($wp) {
    if ($_GET['dynamic-css'] && $_GET['dynamic-css'] == 'css') {
    require get_stylesheet_directory() . '/library/css/dynamic.css.php';
    exit;
    }
}

While this works and does the job. I know that there must be a better way to do this as I know as much as its a massive benefit having this, its not necessarily ideal.

I have an idea how it would work really well and serve a static file on the front end.

My thinking is that since with wordpress, you can have some functional code in the themes function.php file that runs in the admin. There must be a way with php to generate the css file when the themes options are saved from the admin.

When the theme options are saved, the css.php file is processed but the results are saved to a static css file. Then when the site is loaded on the front end by users, they receive the static file that was generated when the options were saved.

I have all the logic I need to do it and the code I have will do fine from a wordpress point of view. My problem is that my php skills with file handling is scratchy as I hardly ever use it.

So, how would I go about it with php. What I would like to do is copy the generated php code into a static css file with php. I am thinking it would be using

file_get_contents();

Any ideas?

Thanks,

1
  • file_put_contents(). Commented Oct 21, 2011 at 21:43

1 Answer 1

1
$ss_dir = get_stylesheet_directory(); // Shorten code, save 1 call
ob_start(); // Capture all output (output buffering)
require($ss_dir . '/library/css/dynamic.css.php'); // Generate CSS
$css = ob_get_clean(); // Get generated CSS (output buffering)
file_put_contents($ss_dir . '/library/css/static.css', $css, LOCK_EX); // Save it

Regards.

PS: You cannot be a developer with scratchy files' skills. They're not optional.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.