Don’t hesitate to contact us if you have any feedback.

WordPress – Handle theme.json RGB color transparency

WordPress’s theme.json has brought unparalleled ease to theme customization. However, the default color settings, which are typically in hexadecimal format, lack support for transparency. To enhance your theme’s color capabilities, we’ve developed a solution that introduces RGB color values with transparency.

Find out how to do it with HSL here.

The Code

<?php

function add_RGB_values_to_CSS_variables($themeJSON) {
    $data = $themeJSON->get_data();

    if (!empty($data)) {

        if (isset($data['settings']['color']['palette']['theme'])) {
            $rgbColorPalette = [];

            $colorPalette = $data['settings']['color']['palette']['theme'];
            if (!empty($colorPalette)) {
                
                // Query the global styles to find custom color palettes
                $customStyles = false;
                $activeThemeSlug = get_stylesheet();
                $dbCustomStyles = get_posts([
                    'name' => "wp-global-styles-{$activeThemeSlug}",
                    'post_type' => 'wp_global_styles',
                    'post_status' => 'publish'
                ]);

                if (!empty($dbCustomStyles)) {
                    $customStyles = json_decode($dbCustomStyles[0]->post_content, true);
                }

                // find occurences in custom palette and replace them in the original one
                if ($customStyles && isset($customStyles['settings']['color']['palette']['theme'])) {
                    $customPalette = $customStyles['settings']['color']['palette']['theme'];

                    $colorPalette = array_map(function ($value) use ($customPalette) {
                        $customValueKey = array_search($value['slug'], array_column($customPalette, 'slug'));

                        return $customValueKey ? $customPalette[$customValueKey] : $value;
                    }, $colorPalette);
                }

                // Loop through color palette
                foreach ($colorPalette as $color) {
                    if (!str_contains($color['slug'], '-hsl') && !str_contains($color['slug'], '-rgb')) {
                        // Convert values in rgb
                        $hexColor = str_replace('#', '', $color['color']);
                        if (strlen($hexColor) > 3) {
                            $tempColor = str_split($hexColor, 2);
                        } else {
                            $tempColor = str_split($hexColor);
                        }
                        $rgbColor = hexdec($tempColor[0]) . ',' . hexdec($tempColor[1]) . ',' . hexdec($tempColor[2]);

                        $rgbColorPalette["{$color['slug']}-rgb"] = $rgbColor;
                    }
                }
            }

            if (!empty($rgbColorPalette)) {
                // Sort array
                ksort($rgbColorPalette);

                // Update interpreted theme.json values
                return $themeJSON->update_with(
                    [
                        'version' => 2,
                        'settings' => [
                            'custom' => $rgbColorPalette,
                        ],
                    ]
                );
            }
        }
    }

    return $themeJSON;
}
add_filter('wp_theme_json_data_theme', 'add_RGB_values_to_CSS_variables');

Our custom PHP function, add_RGB_values_to_CSS_variables, augments your theme’s color configuration by converting hex color codes to their RGB equivalents. This unlocks the ability to manipulate color transparency directly within your CSS, using the alpha channel in RGBA color values.

How It Works

The function performs several key tasks:

  1. Accesses the color settings from the theme.json data.
  2. Searching for custom color palettes that may have been selected by the site administrator in the editor styles page.
  3. Merges the custom colors with the standard palette.
  4. Converts each color from hexadecimal to RGB format, preparing for transparency use.
  5. Organizes the new RGB color values and updates the theme.json data accordingly.

Advantages of RGB with Transparency

RGB color values with transparency offer significant benefits:

  • Transparency Handling: Directly control the transparency of colors through the alpha channel in RGBA.
  • Precise Color Customization: Fine-tune colors with specific RGB values for a perfect match.
  • Enhanced Design Options: Create more dynamic and adaptable designs with transparent color overlays and effects.

Implementation

By hooking into the wp_theme_json_data_theme filter, the function seamlessly enhances the theme.json structure with RGB values. This enhancement is automatically reflected in your theme, ready for use in your CSS with transparency features.

When you add the snippets to your theme, you’ll find the new css variables attached to the body tag. It’ll be in the form of --wp--custom--color-name-rgb.

body {
  --wp--preset--color--base: #f0f0f0;
  --wp--preset--color--base-2: #cfd8dc;
  --wp--preset--color--contrast: #37474f;
  --wp--preset--color--contrast-2: #263238;
  --wp--preset--color--contrast-3: #546e7a;
  --wp--preset--color--accent: #29b6f6;
  --wp--preset--color--accent-2: #38deef;
  --wp--preset--color--black: #000;
  --wp--preset--color--white: #fff;
  --wp--preset--color--info: #17a2b8;
  --wp--preset--color--success: #28a745;
  --wp--preset--color--error: #dc3545;
  --wp--preset--color--warning: #ffc107;

  // RGB values added by the snippet
  --wp--custom--accent-2-rgb: 56,222,239;
  --wp--custom--accent-rgb: 41,182,246;
  --wp--custom--base-2-rgb: 207,216,220;
  --wp--custom--base-rgb: 249,249,249;
  --wp--custom--black-rgb: 0,0,0;
  --wp--custom--contrast-2-rgb: 38,50,56;
  --wp--custom--contrast-3-rgb: 84,110,122;
  --wp--custom--contrast-rgb: 55,71,79;
  --wp--custom--error-rgb: 220,53,69;
  --wp--custom--info-rgb: 23,162,184;
  --wp--custom--success-rgb: 40,167,69;
  --wp--custom--warning-rgb: 255,193,7;
  --wp--custom--white-rgb: 15,15,15;
}

Then you can use theses new variables like so:

body {
  background-color: rgba(var(--wp--custom--accent-rgb), 0.2);
}

Elevate Your Theme Design

With RGB transparency support, your theme’s color palette becomes more versatile and expressive. This update simplifies color management and opens up new possibilities for creating visually stunning effects in your WordPress themes.

For more insights on customizing theme.json with PHP, visit Full Site Editing.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *