I’m working on a migration from another CMS to WordPress. The old site had terrible SEO-unfriendly URLs in the format http://example.com?lid=1234
.
We have imported all the posts from the old site into WordPress and are storing the lid
as a custom field.
We would love the old URLs to still work if possible, but as there are about 3,000 posts using .htaccess is out of the question.
So my question is: how would I create a rewrite rule that extracts the lid
value from the URL and redirects to the post that contains it in the custom field? (the lid
value is unique, so there are no worries about more than one post with the same custom field value)
Many thanks
Simon
2 Answers
here is an idea, first add lid
to query_vars:
add_filter('query_vars', 'lid_query_vars');
function lid_query_vars($vars) {
// add lid to the valid list of variables
$new_vars = array('lid');
$vars = $new_vars + $vars;
return $vars;
}
then use parse_request
hook to create your redirect
add_action('parse_request', 'lid_parse_request');
function lid_parse_request($wp) {
// only process requests with "lid"
if (array_key_exists('lid', $wp->query_vars) && $wp->query_vars['lid'] != '') {
$args = array('meta_key' => 'lid', 'meta_value' => $wp->query_vars['lid']);
$redirect_to_post = get_posts($args);
foreach($redirect_to_post as $p){
$link = get_permalink($p->ID);
wp_redirect( $link , 301 );
exit;
}
}
}