Make WordPress Core

Ticket #21013: 21013.fix-existing-slugs.php

File 21013.fix-existing-slugs.php, 1.9 KB (added by SergeyBiryukov, 14 years ago)
Line 
1<?php
2require 'wp-load.php';
3
4if ( ! function_exists( '_truncate_post_slug' ) ) :
5function _truncate_post_slug( $slug, $length = 200 ) {
6 if ( strlen( $slug ) > $length ) {
7 $decoded_slug = urldecode( $slug );
8 if ( $decoded_slug === $slug )
9 $slug = substr( $slug, 0, $length );
10 else
11 $slug = utf8_uri_encode( $decoded_slug, $length );
12 }
13
14 return rtrim( $slug, '-' );
15}
16endif;
17
18$posts = $wpdb->get_results( "SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'" );
19
20$feeds = $wp_rewrite->feeds;
21if ( ! is_array( $feeds ) )
22 $feeds = array();
23
24foreach ( (array) $posts as $post ) {
25 $original_slug = $post->post_name;
26
27 $decoded_slug = urldecode( $original_slug );
28 if ( $decoded_slug === $original_slug || seems_utf8( $decoded_slug ) )
29 continue;
30
31 $slug = sanitize_title( $post->post_title );
32
33 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = 'post' AND ID != %d LIMIT 1";
34 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post->ID ) );
35
36 if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, 'post' ) ) {
37 $suffix = 2;
38 do {
39 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
40 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post->ID ) );
41 $suffix++;
42 } while ( $post_name_check );
43 $slug = $alt_post_name;
44 }
45
46 $slug = apply_filters( 'wp_unique_post_slug', $slug, $post->ID, 'publish', 'post', 0, $original_slug );
47 $wpdb->update( $wpdb->posts, array( 'post_name' => $slug ), array( 'ID' => $post->ID ) );
48
49 echo 'Post ID: ' . $post->ID . "<br />\n";
50 echo 'Original slug: ' . $decoded_slug . "<br />\n";
51 echo 'Fixed slug: ' . urldecode( $slug ) . "<br />\n";
52}
53
54echo 'All Done!';