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?
wp_insert_post_data
filter instead? Have you tried that?save_post
andwp_insert_post_data
, so how can I visualy update it without refresh the page?