Post slug changed using code doesn’t reflect on editor when post is published

I guess you are using Gutenberg in which case this is non-trivial problem.

Gutenberg saves post data in two steps (two separate http requests, just use developer tools in your browser to check). First, using REST API it saves Gutenberg-ready fields including title, content and slug. Problem is, REST API uses JSON and $_POST is empty array during this save action, so your wp_unique_post_slug hook runs but does nothing. Moreover, metabox/custom field values are not even sent in this JSON request.

Then Gutenberg does another POST request to save other fields, which include old-style metaboxes and Custom Fields. This time $_POST values are available, so your hook is able to update slug value. However this is too late for Gutenberg to change visible slug value in admin interface, as it was done during first request.

This is interesting problem for me, as I had similar use cases in past, but those sites are still using Classic editor. No time for complete solution now, but I would try to create Gutenberg block for your start_date field, set it to store value as meta fields (default for blocks is save inside content field) and add it as mandatory block for your Event CPT, and then try to hook wp_unique_post_slug during REST API call. Just don’t forget, that you don’t have $_POST values and should use $request object provided by REST API to get start_date. A lot to learn about Gutenberg blocks and REST API.

Leave a Comment