How to set custom colors on the Gutenberg color palette?

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.

Default color palette versus the Custom color palette

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.

Use the colors in our Css

To actually make the colors work inside of our theme we have to add a bit of Css for each color like shown below:

Disable the custom color selector

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.

Comments?

If you want to leave a comment, please do so under the copy of this article on Dev.to so i can get back to you.

Follow me on twitter @Vanaf1979 or Dev.to @Vanaf1979 or subscribe to my newsletter to be notified about new articles, and other WordPress development related resources.

Thanks for reading

Share:

Leave a Reply