URL rewrite based on a custom field value

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;
        }
    }
}

Leave a Comment