Rewrite URL Parameter And Force ‘Pretty’ Permalink

I’m trying to pass a variable via a URL parameter and rewrite + force ‘redirect’ it.

In other words, I have:

/dir1/dir2/?my_var=123 

and I want:

/dir1/dir2/123/

Through the following code in my functions.php file, I am able to achieve that:

function setup_filter_rewrites()
{
    add_rewrite_rule('dir1/dir2/([^/]*)/?', 'index.php?pagename=dir1/dir2&my_var=$matches[1]', 'top');
}
add_action( 'init', 'setup_filter_rewrites' );  

function setup_filter_query_vars( $query_vars )
{
    $query_vars[] = 'my_var';
    return $query_vars;
}
add_filter( 'query_vars', 'setup_filter_query_vars' );

However, I’m still able to access the URL via /dir1/dir2/?my_var=123.

Is there a way to force ‘redirect’ (not sure if this is the right way to call this) the URL so that it always serves only the rewritten version? For instance, the way /?page_id=456 forces /my-page-name/ when pretty permalinks are enabled.

Do I need to do anything via .htaccess or am I just missing something in the code?

Thanks in advance!

1 Answer
1

You could force the redirect this way by checking for the get_var query value:

add_action('init','my_redirect_check');
function my_redirect_check() {
    if (isset($_GET['my_var'])) {
        if ($_GET['my_var'] != '') {
            if ($_SERVER["HTTPS"]) {$location = 'https://';}
            else {$location = 'http://';}
            $location .= $_SERVER['SERVER_NAME'];   
            $location .= strtok($_SERVER['REQUEST_URI'],'?');
            $location = trailingslashit($location);
            $location .= $_GET['my_var'];
            $location = trailingslashit($location);                          
            wp_redirect($location); exit;
        }
    }
}

Note: you will lose any other querystring values this way, but you could always rebuild and append those also if needed.

Leave a Comment