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' );
exit;
}
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
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' );
exit;
}
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
Share Improve this question asked Apr 14, 2019 at 11:21 user3309614user3309614 298 bronze badges1 Answer
Reset to default 1If 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/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/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.