How to avoid redirect when rewriting urls with wordpress

I’ve set up a rewrite rule using WordPress own functions.
The rewrite code looks like this:

add_rewrite_rule('^testrule/(.+)?$', 'index.php?p=$matches[1]', 'top');

The rule works and everything, its just that whenever I go to that url, I get redirected which makes the URL changing and I do not want that to happen.

Read More

Any tips?

Related posts

Leave a Reply

2 comments

  1. You probably should use add_permastruct and add_rewrite_tag function it helped in my case. Although I had a little different situation, but the idea would be similar.

    I had custom post type named “guide” and I needed custom URLs for it (different than the custom post name) plus I was using post slugs in URLs, here is my solution:

    add_action('init', 'custom_permastruct_rewrite');
    function custom_permastruct_rewrite() {
        global $wp_rewrite;
    
        $wp_rewrite->add_rewrite_tag("%guide_slug%", '([^/]+)', "post_type=guide&name=");
        $wp_rewrite->add_permastruct('my_rule', '/my_custom_name/%guide_slug%', false);
    }
    

    So when you go to the address:
    http://example.com/my_custom_name/my_post_slug
    under the above URL it displays content from:
    http://example.com/?post_type=guide&name=my_post_slug
    (without redirecting to the last address)

    You can adapt the “post_type=guide&name=” to your needs, for instance you can look for post by id – so putting there “p=” would display content from: http://example.com/my_custom_name/24 to http://example.com/?p=24

  2. some plugins (like Custom Permalinks) can redirect to correct url

    add_rewrite_rule('^testrule/(.+)?$', 'index.php?disable_redirect=1&p=$matches[1]', 'top');
    
    add_filter('query_vars', 'my_public_query_vars');
    function my_public_query_vars($qv)
    {
        $qv[] = 'disable_redirect';
        return $qv;
    }
    
    add_filter('wp_redirect', 'my_disable_redirect');
    function my_disable_redirect($location)
    {
        //var_dump(debug_backtrace());//if you want know who call redirect
        $disable_redirect = get_query_var('disable_redirect');
        if(!empty($disable_redirect)) return false;
        return $location;
    }