Bulk Rebuild Slugs From Titles
Adds a "Rebuild slug from title" bulk action that regenerates the URL slug of the selected drafts or posts from their current titles, handy after importing content with messy slugs.
Opens WPIDE on
Code
add_filter( 'bulk_actions-edit-post', function ( $actions ) {
$actions['wpide_rebuild_slug'] = 'Rebuild slug from title';
return $actions;
} );
add_filter( 'bulk_actions-edit-page', function ( $actions ) {
$actions['wpide_rebuild_slug'] = 'Rebuild slug from title';
return $actions;
} );
$wpide_rebuild_slugs = function ( $redirect, $action, $post_ids ) {
if ( 'wpide_rebuild_slug' !== $action ) {
return $redirect;
}
$done = 0;
foreach ( $post_ids as $post_id ) {
$post = get_post( $post_id );
if ( ! $post || ! current_user_can( 'edit_post', $post_id ) || '' === trim( $post->post_title ) ) {
continue;
}
$slug = wp_unique_post_slug( sanitize_title( $post->post_title ), $post->ID, $post->post_status, $post->post_type, $post->post_parent );
if ( $slug !== $post->post_name ) {
wp_update_post( array( 'ID' => $post->ID, 'post_name' => $slug ) );
$done++;
}
}
return add_query_arg( 'wpide_slugs_rebuilt', $done, $redirect );
};
add_filter( 'handle_bulk_actions-edit-post', $wpide_rebuild_slugs, 10, 3 );
add_filter( 'handle_bulk_actions-edit-page', $wpide_rebuild_slugs, 10, 3 );
add_action( 'admin_notices', function () {
if ( isset( $_GET['wpide_slugs_rebuilt'] ) ) {
printf( '<div class="notice notice-success is-dismissible"><p>Rebuilt %d slugs.</p></div>', absint( $_GET['wpide_slugs_rebuilt'] ) );
}
} );
Notes
Changing the slug of a published post changes its URL; WordPress remembers the old slug and redirects it, but update internal links too.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.