Skip to content

Instantly share code, notes, and snippets.

@mokoshalb
Forked from ryandonsullivan/fixlinks.php
Last active November 16, 2017 09:08
Show Gist options
  • Save mokoshalb/71783fe33bbd68074b9779ef55b6f25a to your computer and use it in GitHub Desktop.
Save mokoshalb/71783fe33bbd68074b9779ef55b6f25a to your computer and use it in GitHub Desktop.
Fix Blogger post permalinks after import into WordPress
<?php
/**
* Rewrite WordPress URLs to match Blogger permalinks exactly.
*
* This script is intended for one time use only after importing Blogger
* content into WordPress and should be removed from the server immediately
* after the script has run one time. It shouldn't be needed again after the
* initial rewrite.
*
* @version 0.1.0
* @author WP Site Care
* @link http://www.wpsitecare.com/import-blogger-to-wordpress/
*/
require_once 'wp-load.php';
/**
* Get all posts with blogger permalinks.
*
* @since 0.1.0
* @access public
* @global $wpdb
* @return array|bool $posts an array of WP_Post objects withe blogger permalinks
*/
function sitecare_get_blogger_posts() {
global $wpdb;
$posts = (array) $wpdb->get_results(
"SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = 'blogger_permalink'"
);
return empty( $posts ) ? false : $posts;
}
/**
* Update posts to match their previous blogger permalink structure.
*
* @since 0.1.0
* @access public
* @global $wpdb
* @return bool true if posts have been updated
*/
function sitecare_fix_blogger_permalinks() {
global $wpdb;
$wpdb->show_errors = true;
$updated = false;
$delete = '<h1>Please delete this file immediately.</h1>';
if ( ! $posts = sitecare_get_blogger_posts() ) {
echo '<h2>There are no posts to update.</h2>';
echo $delete;
return $updated;
}
foreach ( $posts as $post ) {
if ( ! is_object( $post ) ) {
continue;
}
$slug = isset( $post->meta_value ) ? explode( '/', $post->meta_value ) : false;
if ( ! $slug || ! isset( $slug[3], $post->post_id ) ) {
continue;
}
$slug = explode( '.', $slug[3] );
if ( ! isset( $slug[0] ) ) {
continue;
}
$wpdb->query( $wpdb->prepare(
"UPDATE $wpdb->posts SET post_name = %s WHERE ID = %s", $slug[0], $post->post_id
) );
if ( $wpdb->last_error ) {
echo $wpdb->last_error;
} else {
$updated = true;
$title = get_the_title( $post->post_id );
echo "<p>The permalink for <i>{$title}</i> has been updated to <code>{$slug[0]}</code></p>";
}
}
if ( $updated ) {
echo '<h2>Your permalinks have been fixed.</h2>';
echo $delete;
}
return $updated;
}
sitecare_fix_blogger_permalinks();
@mokoshalb
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment