How to set custom gradient colors in Gutenberg.
As of WordPress 5.4 gradient colors in Gutenberg are no longer marked as experimental. Meaning we can start using them in our production sites. Now the default gradients are very creative but a bit loud. So we might want to set some custom gradients so our clients don’t turn our carefully designed websites in to a complete carnival.
To remove the default gradient’s and set some custom colors 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 theme_custom_gradients.
Inside out new theme_custom_gradients function we use the add_theme_support function to enable the editor-gradient-presets theme support. As the second argument we pass an array containing arrays defining our custom gradient 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.
- $gradient: The actual gradient. Check out Css linear-gradient to learn more.
- $slug: A unique slug that we can use in our Css to set the actual gradient.
Use our custom gradients in our Css
To actually make the gradients work inside of our theme we have to add a bit of Css for each gradient like shown below:
Disable Gutenberg gradient colors
In some cases we might want to disable the use of gradients all together. In those cases we can use the code snippet below.
With the code above we add a action to the after_setup_theme hook and register a callback function called disable_editor_gradients.
Inside the disable_editor_gradients function we use the add_theme_support function to add support for disable-custom-gradients (A bit counter intuitive, but it is what it is). Then we also set an empty array for the editor-gradient-presets theme support to remove the default gradients.
IIf 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