The Gutenberg editor offers a great color palette with a custom color picker. But especially in client websites you may want to limit the choices to a predefined set of colors so that clients don't make a true circus of their carefully designed website.
To achieve this we can use the code snippet below.
With the code above we add an action to the after_setup_theme hook and register a callback function called change_gutenberg_color_palette.
Inside the change_gutenberg_color_palette function we use the add_theme_support function to enable the editor-color-palette theme support. As the second argument we pass an array containing arrays defining our custom colors.
Each sub-array contains three key/value pairs. namely:
- $name: The name we want to display inside the editor. Note that we use the __() function to make these names translatable.
- $slug: A unique slug that we can use in our Css to change the actual colors.
- $color: The hex color value.
To actually make the colors work inside of our theme we have to add a bit of Css for each color like shown below:
The code above still leave our users the ability to use the custom color picker to make their own colors. So to be save we can also disable this feature with the code below:
With the code above we add another action to the after_setup_theme hook and register a callback function called disable_custom_color_picker.
Inside the disable_custom_color_picker function we use the add_theme_support function once again but this time we add support for disable-custom-colors. (A bit counter intuitive, but it is what it is.)
This removes the "Custom color" link from the palatte like shown in the image below.
Thanks for reading