WordPress Rewrite

The question:

I’m trying to get http://example.com/site/vendors/?u=abc to rewrite to http://example.com/site/vendors/abc but I can’t for the life of me figure out how to get the url rewrites to work.

/site/ is the root directory for my WP installation
/vendors/ is a page

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

assuming u is a custom query var, you have to first add it to the array of recognized query vars:

function wpa_query_vars( $query_vars ){
    $query_vars[] = 'u';
    return $query_vars;
}
add_filter('query_vars', 'wpa_query_vars');

Then add an internal rewrite rule that accepts anything appended to vendors and passes that as the u query var:

function wpa_rewrite(){
    add_rewrite_rule(
        'vendors/([^/]+)/?$',
        'index.php?pagename=vendors&u=$matches[1]',
        'top'
    );
}
add_action( 'init', 'wpa_rewrite' );

Make sure to flush rewrite rules once for this rule to be added, you can also do this by just visiting the Settings > Permalinks admin page.

Then in the template, you can access the value of u via get_query_var():

$vendor = get_query_var( 'u' );

Method 2

I believe this is what you are looking for:

RewriteRule ^/site/vendors/([^/]*)$ /site/vendors/?u=$1 [L]


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment