Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save grandeto/bf088536fbb43173f57b8ed543df3ea0 to your computer and use it in GitHub Desktop.
Save grandeto/bf088536fbb43173f57b8ed543df3ea0 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