Created
March 26, 2023 15:53
-
-
Save sethrubenstein/341d05b70459cd20a3ea979382d15ba8 to your computer and use it in GitHub Desktop.
Provides an example of how to extract your color palette from a theme.json file and create styles dynamically.
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
<?php | |
function generate_css_from_theme_settings() { | |
if ( !function_exists('wp_get_global_settings') ) { | |
return new WP_Error('missing_function', 'wp_get_global_settings() is missing'); | |
} | |
$colors = wp_get_global_settings(); | |
$colors = $colors['color']['palette']['theme']; | |
ob_start(); | |
foreach( $colors as $color ) { | |
$slug = $color['slug']; | |
$color = $color['color']; | |
?> | |
.wp-block-my-block-name.has-<?php echo $slug; ?>-color path.my-target-path { | |
fill: <?php echo $color; ?> !important; | |
} | |
<?php | |
} | |
$styles = ob_get_clean(); | |
return $styles; | |
} | |
function enqueue_custom_fill_styles() { | |
$styles = generate_css_from_theme_settings(); | |
if ( is_wp_error($styles) ) { | |
return; | |
} | |
wp_add_inline_style( 'my-block-style-handle', $styles ); | |
} | |
add_action('wp_enqueue_scripts', 'enqueue_custom_fill_styles'); | |
add_action('enqueue_block_editor_assets', 'enqueue_custom_fill_styles'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment