Using a block theme, I was curious how to add custom CSS styling to the block editor without explicit enqueuing a separate CSS file. I wanted to do it the same way as the block editor.

After some researching, I found the way the block editor is doing it in WordPress. It is part of the block editor settings and either located in the index defaultEditorStyles (where basically the file content of wp-includes/css/dist/block-editor/default-editor-styles.css is inserted) or the index styles. The latter contains all styles for the current page to render. It is an array containing a list of arrays, all with the index css and source, where the first one contains the actual CSS code and the latter the identifier of the source where the code comes from.

Using the filter block_editor_settings_all, you can extend the styles array and add your own CSS. In my case, I explicitly set a custom text color if a specific background color is selected.

This is what the code looks like:

/**
 * Enqueue inline styles for the editor.
 * 
 * @param	array	$settings Editor settings
 * @return	array Updated editor settings
 */
public static function my_theme_enqueue_inline_styles( array $settings ): array {
	// colors
	$settings['styles'][] = [
		'css' => '.has-blue-background-color a {
			color: var(--wp--preset--color--light);
		}
		
		.has-dark-background-color a {
			color: var(--wp--preset--color--light);
		}
		
		.has-dark-blue-background-color a {
			color: var(--wp--preset--color--orange);
		}
		
		.has-orange-background-color a {
			color: var(--wp--preset--color--dark-blue);
		}',
		'source' => 'my-theme',
	];
	
	return $settings;
}

\add_filter( 'block_editor_settings_all', 'my_theme_enqueue_inline_styles' );
Code language: PHP (php)

This way you don’t need to enqueue a separate CSS file into the block editor in WordPress at all.

Leave a Reply

Your email address will not be published. Required fields are marked *