I have a function in my wordpress that load a dynamic css. I checked that this admin-ajax.php call made the website slow (+5s) about.

add_action( 'wp_enqueue_scripts', 'theme_custom_style_script', 12 );

function theme_custom_style_script() {
    wp_enqueue_style( 'dynamic-css', admin_url('admin-ajax.php').'?action=dynamic_css', '');

add_action('wp_ajax_dynamic_css', 'dynamic_css');

function dynamic_css() {
    require( get_template_directory().'/css/custom.css.php' );

Can i save the output of this file in a folder each time i make an edit on admin , and load such a css link instead of load everytime via admin-ajax ? or call in different way to avoid this issue ? Thanks

1 Answer 1


If you want to save the generated css to a file, take a look at file_get_contents() and file_put_contents() native PHP functions. https://www.php.net/manual/en/function.file-put-contents.php

You can also find some Q&A's on the topic both in SO and WPSE, e.g. https://stackoverflow.com/questions/25559913/write-from-wordpress-plugin-to-text-file-with-php

You can then enqueue the created css file inside wp_enqueue_scripts like any other css file. You might want to wrap the enqueue inside a file_exists conditional check to avoid potential errors.

Another option could be that you enqueue the dynamic css in wp_enqueue_scripts, but wrapped in a suitable if statement.

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.