Skip to content

Instantly share code, notes, and snippets.

@mikedance
Created October 9, 2018 19:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikedance/ba2bb268570bd7cf22b258e88bb0af94 to your computer and use it in GitHub Desktop.
Save mikedance/ba2bb268570bd7cf22b258e88bb0af94 to your computer and use it in GitHub Desktop.
Generate CSS class rules for custom color palettes and font sizes in WordPress/Gutenberg
/**
* Generate CSS for Gutenberg's has-*-color, has-*-background-color
* and has-*-font-size, based on our colors/sizes. This works on the
* frontend and in the backend editor.
*/
add_action( 'wp_print_scripts', function() {
$string = '<style>';
// color palette
$palette = get_theme_support( 'editor-color-palette' );
$palette = $palette[0];
foreach( $palette as $color ) {
$color = wp_parse_args( $color, array(
'name' => '',
'slug' => '',
'color' => '',
) );
if ( ! $color['slug'] ) {
$color['slug'] = sanitize_title( $color['name'] );
if ( ! $color['slug'] ) {
continue;
}
}
$hex = $color['color'];
if ( !$hex ) {
continue;
}
$class1 = '.has-' . $color['slug'] . '-color';
$class2 = '.has-' . $color['slug'] . '-background-color';
$string .= $class1 . ','
. $class1 . ' a,'
. $class1 . ' a:hover,'
. $class1 . ' a:focus'
. '{color:' . $hex . ';border-color:' . $hex . ';}';
$string .= $class2 . '{background-color:' . $hex . '}';
}
// font sizes
$sizes = get_theme_support( 'editor-font-sizes' );
$sizes = $sizes[0];
foreach( $sizes as $size ) {
$size = wp_parse_args( $size, array(
'size' => 0,
'slug' => '',
) );
if ( ! $size['slug'] || ! $size['size'] ) {
continue;
}
$size['slug'] = sanitize_title( $size['slug'] );
$size['size'] = (int) $size['size'];
$string .= '.has-' . $size['slug'] . '-font-size{font-size:' . $size['size'] . 'px}';
}
$string .= '</style>';
echo $string;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment