When we customize a theme in WordPress in custom CSS, so it creates backend custom CSS file and I have to do these tasks which I cant understand openly:

  1. To save this CSS in a file in the upload folder dynamically.
  2. And render the custom CSS from the file. (that was just generated dynamically in 1st step above.)
  3. Remove it from the HTML head section. Otherwise, the custom CSS will be rendered twice. Can anybody help?

1 Answer 1


Please use this method:

// Lets create some test CSS code
$css = '/* Some test CSS */ body {background:red;}';

// Stash CSS in uploads directory
require_once( ABSPATH . 'wp-admin/includes/file.php' ); // We will probably need to load this file
global $wp_filesystem;
$upload_dir = wp_upload_dir(); // Grab uploads folder array
$dir = trailingslashit( $upload_dir['basedir'] ) . 'some-folder/'; // Set storage directory path

WP_Filesystem(); // Initial WP file system
$wp_filesystem->mkdir( $dir ); // Make a new folder for storing our file
$wp_filesystem->put_contents( $dir . 'style.css', $css, 0644 ); // Finally, store the file :D
  • 1
    Welcome to wpse! Consider adding explination about this code, what it does, how it solves OPs problem, how and where to implement this code. Commented Oct 21, 2021 at 9:44
  • To use this code, create a simple custom WPPlugin and place this code in this plugin. Activate this plugin and the code will work.
    – Ahmed Ali
    Commented Oct 22, 2021 at 6:06

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.