I've a CPT (lets say Event
) with a custom date field (start_date
). I'm trying to generate the post slug (post_name
) as start_date
+ post_title
(separated by -
).
I've tried using the filter wp_unique_post_slug
as well as wp_insert_post_data
to modify post_name
. When I publish the post, the slug gets changed internally but it doesn't reflect on admin UI. Only when I refresh the page (edit the post again) the new slug gets displayed properly.
What could be the reason and how do I ensure that the generated slug gets displayed immediately when I publish the post?
One observation: wp_unique_post_slug
filter is invoked 4 times when I publish the post. Out of the 4 invocations only 3rd invocation gets the any data in $_POST
and in turn the logic for editing the slug gets executed only during 3rd invocation.
Here is the code sample that I'm using, if that helps:
public function cpt_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
if( ! in_array($post_type, array('Event', 'CPT2') ) ) return $slug;
error_log(var_export($_POST, true));
if(isset($_POST['start_date'])) {
// remove any date from post slug
$slug = preg_replace( '/^\d{4}-\d{2}-\d{2}-/', '', $slug );
$slug = $_POST['start_date'] . '-' . $slug;
}
return $slug;
}