Created
October 9, 2018 19:50
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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