1

I'm trying to edit the slug field on the right panel of Gutenberg editor and edit its content based on a custom field.

I noticed that I can access the field by using this JavaScript to interact with the React Component:

wp.data.select('core/editor').getEditedPostSlug();

My question is: How can I edit this field in JavaScript?

There's no .setEditedPostSlug() method for this and select the field in normal JS script is impossible because the field's ID is generated each time the panel is opened and if we close the panel, the field disappear from the DOM.

1

1 Answer 1

2

I've found the way to edit the slug's field. Just simply use:

wp.data.dispatch('core/editor').editPost({slug: 'my-slug-value-here'});

With an event listener like this, I can dynamically change the slug field based on a custom field:

jQuery(document).ready(() => {

    const acfField = 'field_61f8bacf53dc5';
    const inputShortTitle = document.getElementById('acf-' + acfField);

    const slugify = (str) => {
        return str.toLowerCase().replace(/ /g, '-')
            .replace(/-+/g, '-').replace(/[^\w-]+/g, '');
    }

    const updateSlug = () => {
        wp.data.dispatch('core/editor').editPost({slug: slugify(inputShortTitle.value)});
    }

    if (inputShortTitle !== null) {
        inputShortTitle.addEventListener('input', () => updateSlug());
    }
});

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.