gutenberg-best-practices icon indicating copy to clipboard operation
gutenberg-best-practices copied to clipboard

Add documentation about custom class name generation

Open fabiankaegy opened this issue 2 years ago • 1 comments

In a discussion with @iansvo we've uncovered that core only generates the has-${slug}-color etc class names when you are using theme.json older themes that use the add_theme_support will only get the custom properties defined but the themes will have to manually add the classes.

This should be documented somewhere.

fabiankaegy avatar May 16 '22 11:05 fabiankaegy

Here's an example of some code that I've written to address this on themes that do not currently leverage theme.json.

This is a reduced example that shows the point of execution for the changes to provide full context.

<?php
add_action( 'after_setup_theme',  'theme_setup' );

function theme_setup() {
	// ...

	// add basic Brand colors to gutenberg color selector
	add_theme_support( 'editor-color-palette', color_palette() );

	// Output CSS for the color palette here
	add_action( 'wp_head',  'output_color_palette_styles', 999 );
}

/**
 * Return Theme Color Palette
 *
 * @return array Theme Color Palette
 */
function color_palette() {
	return [
		[
			'name'  => esc_html__( 'Bazinga', 'wmb' ),
			'slug'  => 'bazinga',
			'color' => 'var(--color-bazinga)',
		],
	];
}

/**
 * Add CSS for the color palette to head tag
 *
 * @return void
 */
function output_color_palette_styles() {
	$color_palette = color_palette();

	echo "<style id='color-palette-styles'>\n";

	foreach ( $color_palette as $color ) {
		$slug  = $color['slug'];
		$value = $color['color'];

		echo esc_html( ".has-background.has-{$slug}-background-color { background-color: $value; }\n" );
		echo esc_html( ".has-text-color.has-{$slug}-color { color: $value; }\n" );
	}

	echo '</style>';
}

iansvo avatar May 16 '22 13:05 iansvo