During a chat this morning with friends from the WordPress space, the topic of the long naming convention used for the CSS custom properties came up, and how shortening them can beneficial.
It reminded me that when I first brought my base WordPress Theme with me when I came to Say Hello, I used a much shorter naming convention for presets I’d been using for the past few years. This isn’t technically useful in any other way than it slightly reduces the amount of CSS code, but can be very time-saving when writing custom CSS based on the presets.
For an example, the colour presets have long-winded names like --wp--preset--color--white
or --wp--preset--color--primary
. These specific naming conventions are good because they are comparatively unique. Most developers who work with WordPress will avoid adding a conflict. However, it can be productive to use shorter names in custom code.
In order to allow you to use shorter names (like --shtc--white
), with my chosen prefix SHTC meaning “Say Hello Theme Colour”, the easiest solution is to add aliases for the WordPress colour palette entries. This will ensure that you can use the aliases in your own code, without breaking the core functionality. By fetching the colour palette from the theme.json file, you can also ensure that the aliases all match the preset colours available in the theme.json file.
This piece of code will do just that, and output the aliased CSS Custom Properties as inline rules on every page.
add_action('wp_enqueue_scripts', function () {
// Get merged theme.json data
$merged_theme_json = WP_Theme_JSON_Resolver::get_merged_data('theme')->get_data();
// Extract colors from theme.json settings
$colors = $merged_theme_json['settings']['color']['palette'] ?? [];
// Return early if there are no colors
if (empty($colors)) {
return;
}
// Generate CSS custom property aliases
$aliases = [];
foreach ($colors as $color) {
$aliases[] = "--shtc--{$color['slug']}: var(--wp--preset--color--{$color['slug']});";
}
// Combine aliases into a single CSS string
$aliases_css = ":root {\n" . implode("\n", $aliases) . "\n}";
// Enqueue a dummy stylesheet (required for wp_add_inline_style to work)
wp_register_style('shtc-theme-color-aliases', false);
wp_enqueue_style('shtc-theme-color-aliases');
// Add inline CSS
wp_add_inline_style('shtc-theme-color-aliases', $aliases_css);
});
Leave a Reply