How can I add template colors (i.e., those black and pastel shades) to
ColorPalette(“Input border color”)?
In Gutenberg, you can get the block color palette in two ways:
-
Use
getSettings()in the block editor’s data (core/block-editor). E.g.import { select } from '@wordpress/data'; const colorPalette = select( 'core/block-editor' ).getSettings().colors; // PS: You can also run wp.data.select( 'core/block-editor' ).getSettings().colors // via the console. -
Or particularly in a function component, use the
useSettinghook in the@wordpress/block-editororwp.blockEditorpackage (which uses thegetSettings()above). Note though, in WordPress 5.7, the hook was nameduseEditorFeature. So for example:import { useSetting } from '@wordpress/block-editor'; // Then in your EDIT FUNCTION, use useSetting( 'color.palette' ): const colorPalette = useSetting( 'color.palette' );
And just so that you know, in PHP, you can use get_theme_support( 'editor-color-palette' ) to get the above palette.
Example/Demo using the useSetting hook (in WordPress 5.8)
Note that in this example, I added the colors in the question (red, white and blue) and then the color.palette above.
-
In my
index.jsfile, I got this at the top: (Note though, I omitted theregisterBlockTypestuff)import { useBlockProps, InspectorControls, useSetting, } from '@wordpress/block-editor'; import { PanelBody, TextControl, ColorPalette, } from '@wordpress/components'; const CUSTOM_COLORS = [ { color: '#f00', name: 'Red', }, { color: '#fff', name: 'White', }, { color: '#00f', name: 'Blue', }, ]; -
And here’s my
editfunction:function Edit( { attributes, setAttributes } ) { const { content, borderColor } = attributes; return ( <> <InspectorControls> <PanelBody> <TextControl label="Content" value={ content } onChange={ ( value ) => setAttributes( { content: value } ) } /> <div> <p>Input border color</p> <ColorPalette value={ borderColor } colors={ [ ...CUSTOM_COLORS, ...useSetting( 'color.palette' ) ] } onChange={ ( value ) => setAttributes( { borderColor: value } ) } /> </div> </PanelBody> </InspectorControls> <div { ...useBlockProps( { style: { border: '2px solid ' + borderColor, padding: '10px 15px', }, } ) } > { content } </div> </> ); } -
So the above
InspectorControlsoutputs this (the theme is Twenty Twenty-One 1.4 which has 10 colors in the block color palette — see source on Trac):
