Custom rewrite_rules – only pass numbers and not alphabetic characters

I’m trying to add a rewrite rule to pass a var to a custom page template.

For some weird reason it only excepts numbers in the variables, when I type in characters other then number it directs to 404.

Read More

For example

This works: http://example.com/reco/9080

But this doesn’t: http://example.com/reco/abcd (redirects to 404)

This is my code:

function add_rewrite_rules($wp_rewrite) {
        add_rewrite_rule('reco/([^/]*)/?', 'index.php/reco/?b=$1', 'top');
}
add_action('generate_rewrite_rules', 'add_rewrite_rules');


function query_vars($public_query_vars) {
    $public_query_vars[] = "b";
    return $public_query_vars;
}
add_filter('query_vars', 'query_vars');

Related posts

Leave a Reply

1 comment

  1. Instead of index.php/reco/?b=$1, try this:

    "$wp_rewrite->index?pagename=reco&b=" . $wp_rewrite->preg_index( 1 )
    

    You should also append a $ to your reco/([^/]*)/? regex to ensure the rule only matches the entire path, and not just the beginning.

    Then flush your rules afterwards (just re-save your permalink settings in admin).

    Update: Try using the page_rewrite_rules filter instead, and use get_query_var( 'b' ):

    function wpse_139259_page_rules( $rules ) {
        return array(
            'reco/([^/]+)/?$' => 'index.php?pagename=reco&b=$matches[1]',
        ) + $rules;
    }
    
    add_filter( 'page_rewrite_rules', 'wpse_139259_page_rules' );