0

The excerpt panel in the Gutenberg block editor has the label text "Write an excerpt (optional)"

How can this text be edited? Specifically I want to remove "(optional)".

I've attempted to target the label with JS, but neither of the below work (just see an empty collection in the console). If I run document.getElementsByClassName('e1puf3u2') in the console, I get back the label element.

wp.domReady(() => {
  let labels = document.getElementsByClassName('e1puf3u2');
  console.log(labels);
});


document.addEventListener("DOMContentLoaded", function(event) {
  let labels = document.getElementsByClassName('e1puf3u2');
  console.log(labels);
});

enter image description here

1 Answer 1

1

That label is a translatable text and its translation is retrieved using wp.i18n.__(), so you can change the text like you could in PHP via the gettext filter, except that in JS/Gutenberg, you'd use i18n.gettext.

Working example:

// Define our filter callback.
function myPluginGettextFilter( translation, text, domain ) {
    if ( text === 'Write an excerpt (optional)' ) {
        return 'Write an excerpt';
    }

    return translation;
}

// Adding the filter
wp.hooks.addFilter(
    'i18n.gettext',
    'my-plugin/override-write-an-excerpt-label',
    myPluginGettextFilter
);

And another way to change the text, without using hooks, is by using wp.i18n.setLocaleData() like so:

wp.i18n.setLocaleData({
    'Write an excerpt (optional)': [
        'Write an excerpt'
    ]
});
/* The format is:
wp.i18n.setLocaleData({
    '<original text>': [
        '<singular translation>',
        '<plural translation>'
    ]
});

// but just pass one translation (one array item) if there are no plural
// translation available, or if both singular and plural translations are
// identical
*/

And remember to load the script's dependency, i.e. wp-hooks for the 1st example, and wp-i18n for the 2nd example.

1
  • 1
    Works perfectly, thanks @SallyCJ
    – anu
    Commented Aug 2, 2021 at 8:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.