Gutenberg Editor: dynamicaly change slug field with an ACF field

I have a custom field with ACF named short_title and I want the post's slug based on this field instead of the post title field.

I already wrote this code:

function testSlug($post_id)
{
    if (get_post_type($post_id) == 'my-custom-post-type') {
        if (defined('DOING_AUTOSAVE'  DOING_AUTOSAVE)) {
            return;
        }

        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        remove_action('save_post', 'testSlug');
        $updated_post              = [];
        $updated_post['ID']        = $post_id;
        $updated_post['post_name'] = sanitize_title($_POST['acf']['field_61f8bacf53dc5']);
        wp_update_post($updated_post);
        add_action('save_post', 'testSlug');
        clean_post_cache($post_id);
    }
}
add_action('save_post', 'testSlug');

this works great and edit the slug, but on the editor, the slug field is not synchronised with this field and when we click on Save or Publish button, the slug field is filling with the post title slug.

But, if we refresh the edit page, the correct slug is shown.

I tried to do some JS to synchronise input event of the ACF field with the slug field, but it doesn't work because when the panel is close, the element disapear from the DOM. Plus, even if the panel is open when the page load, the script run too early, when the editor is not fully loaded, and it return undefined because the field have a dynamic ID (inspector-text-control-X, with X is 1, 2, ...).

How can I synchronize the slug field with my custom field? And how can I prevent the event from the post title field to edit the slug field?

Topic block-editor slug permalinks Wordpress

Category Web


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.

About

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