Skip to content

Instantly share code, notes, and snippets.

@Jany-M
Last active June 6, 2021 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Jany-M/a476a3eb6df59dc22faaf6188484af97 to your computer and use it in GitHub Desktop.
Save Jany-M/a476a3eb6df59dc22faaf6188484af97 to your computer and use it in GitHub Desktop.
[WordPress] Automatically rename post slug on post save
<?php
// Change & Save New Permalink if post title was changed
function update_slug_on_edit( $data, $postarr ) {
global $post;
$id = $post->ID;
$status = $post->post_status;
$cpt = get_post_type($id);
$parent = $post->post_parent;
$title = $data['post_title'];
$partial_slug = sanitize_title($title);
$new_slug = wp_unique_post_slug($partial_slug, $id, $status, $cpt, $parent );
if (!wp_is_post_revision($id)) {
$data['post_name'] = $new_slug;
}
return $data;
}
add_filter( 'wp_insert_post_data', 'update_slug_on_edit', 99, 2 );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment