Custom query variable – get wordpress to redirect to nice permalink url

I figured out a solution myself. No javascript required, only another template function. URL building done manually.

The idea is to use the hook ‘template_redirect’, check if the requested page is the corresponding store archive page, then check for $_REQUEST vars there and build a new URL. Finally redirect to this URL.

function my_template_redirect() {
    if ( is_post_type_archive( 'stores' ) ) {
        if ( isset( $_REQUEST['state'] )  ) {
            $myurl = get_post_type_archive_link( 'stores' );
            if (substr($myurl, -1) != "https://wordpress.stackexchange.com/") $myurl .= "https://wordpress.stackexchange.com/";
            $myurl .= "state/";
            $myurl .= trim( sanitize_title_for_query( $_REQUEST['state'] ) ) . "https://wordpress.stackexchange.com/";
            exit( wp_redirect( $myurl ) ) ;
        }
    }
}
add_action( 'template_redirect', 'my_template_redirect' );

Works pretty well. Any corrections/better ideas are welcome of course.