admin管理员组

文章数量:1134247

I am using the following code to rewrite "example?my_var=test" to "example/my_var/test":

function my_query_vars($vars)
{
    $vars[] = 'my_var';
    return $vars;
}

function my_rewrite()
{
    add_filter('query_vars', 'my_query_vars');
    add_rewrite_tag('%my_var%', '([^&]+)');
    add_rewrite_rule('^my_var/(.+)/?$', 'index.php?page_id=16&my_var=$matches[1]', 'top');
}

add_action('init', 'my_rewrite');

This only works, if the page with id 16 is not set as "page_on_front" in the WordPress settings.

  • "page_on_front" = whatever --> above code works
  • "page_on_front" = 16 --> "example/my_var/test" redirects to "example"

Do you have an idea why this is happening?

thanks a lot, Jan

EDIT

I disabled the redirect with this code and it seems to work just fine:

function disable_redirect($redirect_url, $requested_url)
{
    if ( get_query_var( 'my_var' ) )
    {
        return '';
    }
    return $redirect_url;
}

function my_query_vars($vars)
{
    $vars[] = 'my_var';
    return $vars;
}

function my_rewrite()
{    
    add_filter('redirect_canonical', 'disable_redirect', 10, 2);
    add_filter('query_vars', 'my_query_vars');
    add_rewrite_tag('%my_var%', '([^&]+)');
    add_rewrite_rule('^my_var/(.+)/?$', 'index.php?page_id=16&my_var=$matches[1]', 'top');
}

add_action('init', 'my_rewrite');

Do you think this is a good solution? Is there a better way to disable the redirect?

本文标签: phpWordPress addrewriterule not working with pageonfront