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
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' );