<?php
require 'wp-load.php';

if ( ! function_exists( '_truncate_post_slug' ) ) :
function _truncate_post_slug( $slug, $length = 200 ) {
	if ( strlen( $slug ) > $length ) {
		$decoded_slug = urldecode( $slug );
		if ( $decoded_slug === $slug )
			$slug = substr( $slug, 0, $length );
		else
			$slug = utf8_uri_encode( $decoded_slug, $length );
	}

	return rtrim( $slug, '-' );
}
endif;

$posts = $wpdb->get_results( "SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'" );

$feeds = $wp_rewrite->feeds;
if ( ! is_array( $feeds ) )
	$feeds = array();

foreach ( (array) $posts as $post ) {
	$original_slug = $post->post_name;

	$decoded_slug = urldecode( $original_slug );
	if ( $decoded_slug === $original_slug || seems_utf8( $decoded_slug ) )
		continue;

	$slug = sanitize_title( $post->post_title );

	$check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = 'post' AND ID != %d LIMIT 1";
	$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post->ID ) );

	if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, 'post' ) ) {
		$suffix = 2;
		do {
			$alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
			$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post->ID ) );
			$suffix++;
		} while ( $post_name_check );
		$slug = $alt_post_name;
	}

	$slug = apply_filters( 'wp_unique_post_slug', $slug, $post->ID, 'publish', 'post', 0, $original_slug );
	$wpdb->update( $wpdb->posts, array( 'post_name' => $slug ), array( 'ID' => $post->ID ) );

	echo 'Post ID: ' . $post->ID . "<br />\n";
	echo 'Original slug: ' . $decoded_slug . "<br />\n";
	echo 'Fixed slug: ' . urldecode( $slug ) . "<br />\n";
}

echo 'All Done!';
