Gutenberg Editor: dynamically edit slug field based on ACF field

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 to the field by using wp.data.select('core/editor').getEditedPostSlug(); in JavaScript to interact with the React Component. 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 disapear from the DOM.

Topic block-editor slug permalinks Wordpress javascript

Category Web


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());
    }
});

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.