Redirect short-form URL to long-form URL (post_id to post_id + post_name)

I think can do:

add_action('template_redirect', 'my_func');
function my_func(){
    if(is_single()){
        // catch the last string
        preg_match('/(.*)\/(.*?)\//',  $_SERVER['REQUEST_URI'], $new_array);
        $last_phrase= $new_array[2];
        if(is_numeric($last_phrase)){
            $id = $last_phrase;
            header('location: '. get_permalink($id) , true, 301); exit;
        }
    }
}

Leave a Comment