I migrated a site from Tumblr to WordPress and was able to get all the content over (in pieces) using the FeedWordPress plugin. What I am now trying to do is get the old permalink structure to redirect dynamically.
The plugin added a custom field with the old Tumblr permalink (syndication_permalink is the name of the field). Is there a function I can write using wp_redirect to check for this field, and if so redirect to the new permalink URL?
Hey, you might have luck with a prior plugin I wrote (here’s the code itself). It’s a redirect plugin that looks at the URL coming in, checks it against the postmeta table if it’s about to produce a 404, and redirect the user if a match is found.
If you have the entire URI stored in the custom field for a post, it might look something like:
/**
* Redirect old Tumblr URLs to new WP if the URI exists in the database
*/
function tumblr_legacy_redirect() {
global $wpdb; // We're going to use this for the db lookup
// Only run this lookup on URLs that are going to 404 anyway
if ( is_404() ) {
// We're getting the incorrect URI in hopes that it's an old Tumblr link
$requested_url = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
// Prepare the query so we protect ourselves against bad SQL queries
$query = $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='syndication_permalink' AND meta_value="%s"", $requested_url );
$post_id = $wpdb->get_results( $query, 'ARRAY_N' );
// Catch if there are duplicate results in the database
$post_id = $post_id[0][0];
// Build the redirect if the post_id exists
if ( $new_url = get_permalink( $post_id ) ) {
wp_redirect( $new_url, 301 );
} else {
return;
}
} // END - if ( is_404() )
} // END - tumblr_legacy_redirect()
// A good place for our template redirect to hook into
add_action( 'template_redirect', 'tumblr_legacy_redirect' );
Caveat is that I haven’t actually tested the code, so let me know if you run into any errors!