I want to add the support for the gradient colors in highlight option against any selected text. For reference please see this comment. I have seen this stackOverflow thread as well. It provides support to add gradient color on block level. I need it on selected text level as shown in the images
As seen I only have the option of solid colors in toolbar highlight option. Is there any way I can get gradient colors there as well. Any response would be appreciated.
As the gradient editor applies to the block level, the workaround I've found is using the Format API to register a custom format to add a gradient background to selected text within a paragraph block.
Note: The caveat with this method is a predefined gradient in the theme.json is used as the className
and the gradient picker won't appear, as it is a block-level option (see screenshot below).
index.js
import { registerFormatType, toggleFormat } from '@wordpress/rich-text';
import { RichTextToolbarButton } from '@wordpress/block-editor';
const AddGradientButton = ({ isActive, onChange, value }) => {
return (
<RichTextToolbarButton
icon="star-filled"
title="Gradient Background"
onClick={() => {
onChange(
toggleFormat(value, {
type: 'gradient-background/warm-to-cool',
})
);
}}
isActive={isActive}
/>
);
};
registerFormatType('gradient-background/warm-to-cool', {
title: 'Gradient Style',
tagName: 'span', // uses <span>...</span> to wrap the selected text
className: 'has-cool-to-warm-spectrum-gradient-background', // change to name of your predefined gradient
edit: AddGradientButton,
});
Block content saved:
<!-- wp:paragraph -->
<p>Gradients <span class="has-cool-to-warm-spectrum-gradient-background">on text in a paragraph</span> of text.</p>
<!-- /wp:paragraph -->