Gutenberg Editor: dynamicaly change slug field with an ACF field

I’ve found a way to dynamicaly change the slug field with the short title 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());
    }
});
wp.data.dispatch('core/editor').editPost({slug: 'my-slug-value-here'});

is the command that can change React Gutenberg slug field component. No more PHP is needed because when I pressed the Save button, the actual value filled by my script is send to the API.

Leave a Comment