Skip to content

Instantly share code, notes, and snippets.

@SchneiderSam
Last active April 18, 2024 08:29
Show Gist options
  • Save SchneiderSam/73e66ea55d8a04b18af82d2c15ae0c6d to your computer and use it in GitHub Desktop.
Save SchneiderSam/73e66ea55d8a04b18af82d2c15ae0c6d to your computer and use it in GitHub Desktop.
Load Both Customizer and style.css into WordPress Block Editor
<?php
// Load CSS Variables in Editor
add_filter('block_editor_settings_all', function($editor_settings) {
$style_path = get_stylesheet_directory() . '/style.css';
if (file_exists($style_path)) {
$css_style = file_get_contents($style_path);
$editor_settings['styles'][] = ['css' => $css_style];
}
$customizer_css = wp_get_custom_css_post();
if (isset($customizer_css->post_content)) {
$css_customizer = $customizer_css->post_content;
$editor_settings['styles'][] = ['css' => $css_customizer];
}
return $editor_settings;
});
@SchneiderSam
Copy link
Author

This gist provides a comprehensive solution for integrating both the custom CSS added via the WordPress Customizer and the styles from the theme’s style.css file into the WordPress Block Editor. This code snippet uses the block_editor_settings_all filter to inject styles from both sources into the editor’s settings, ensuring a consistent visual experience across the site’s frontend and the block editor interface.

  1. Style.css Integration: The snippet checks for the existence of the style.css file in the theme's directory and, if present, reads its content to add to the editor’s styles array.
  2. Customizer CSS Integration: Additionally, it retrieves any custom CSS specified in the Customizer's "Additional CSS" section and appends this to the editor’s styles array as well.

This approach is beneficial for developers seeking to maintain a uniform appearance throughout the site, including the editing environment, without having to duplicate CSS rules. However, be mindful of potential performance impacts due to loading extensive CSS directly into the editor, and consider using targeted editor-specific stylesheets where appropriate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment