Skip to content

Instantly share code, notes, and snippets.

@mathetos
Last active July 7, 2025 10:38
Show Gist options
  • Save mathetos/d06e8fdae4e3b4240e9d07ea8a471ea6 to your computer and use it in GitHub Desktop.
Save mathetos/d06e8fdae4e3b4240e9d07ea8a471ea6 to your computer and use it in GitHub Desktop.
MC's External CSS for the Customizer
<?php
/**
* Plugin Name: MC's Custom External CSS
* Description: Write Customizer CSS to an external file and enqueue it after theme.css with file-mtime versioning.
* Version: 1.0
* Author: You
*/
// 1. Disable core Customizer inline <style>
/**
* Stop the Customizer “Additional CSS” from being printed on the front-end.
* Put this in functions.php or a small plugin.
*/
add_action( 'init', function () {
if ( ! is_customize_preview() ) {
remove_action( 'wp_head', 'wp_custom_css_cb', 101 );
}
}, 0 );
add_action( 'wp_enqueue_scripts', function() {
wp_dequeue_style( 'custom-css' );
}, 5 );
// 2. Write the Customizer CSS to an external file in uploads/
function cec_write_custom_css() {
$css = wp_get_custom_css(); // get the saved Additional CSS
if ( ! $css ) {
return;
}
$upload_dir = wp_upload_dir();
$file = trailingslashit( $upload_dir['basedir'] ) . 'custom-external.css';
// ensure directory exists
wp_mkdir_p( dirname( $file ) );
file_put_contents( $file, wp_unslash( $css ) );
}
add_action( 'customize_save_after', 'cec_write_custom_css' );
register_activation_hook( __FILE__, 'cec_write_custom_css' );
// 3. Enqueue the external CSS after your theme’s main stylesheet
add_action( 'wp_enqueue_scripts', function() {
$upload_dir = wp_upload_dir();
$file = trailingslashit( $upload_dir['basedir'] ) . 'custom-external.css';
$url = trailingslashit( $upload_dir['baseurl'] ) . 'custom-external.css';
if ( file_exists( $file ) ) {
wp_enqueue_style(
'custom-external',
$url,
[ 'kadence-global' ], // ← replace 'kadence-global' with your theme’s primary handle
filemtime( $file )
);
}
}, 20 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment