views:

79

answers:

2

I have links in my site that pass queries to pages that query from an external database. This works fine e.g.

mysite.com/catalog/?tl=flooring

however i want to rewrite this url to appear as

mysite.com/catalog/flooring

Ive tried modifying the rewrite rules in wordpress but it always displays the index page

add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
add_filter('query_vars','wp_insertMyRewriteQueryVars');
add_filter('init','flushRules');

// Remember to flush_rules() when adding rules
function flushRules(){
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
}

// Adding a new rule
function wp_insertMyRewriteRules($rules)
{
    $newrules = array();
    $newrules['(catalog)/([a-zA-Z0-9 ]+)$'] = '/catalog/?tl=$matches[2]';
    return $newrules + $rules;
}

// Adding the id var so that WP recognizes it
function wp_insertMyRewriteQueryVars($vars)
{
    array_push($vars, 'id');
    return $vars;
}
+1  A: 

Rewrite rules in WordPress don't quite work like how you're expecting them to. All rewrite rules map to a file handler (almost always index.php), not another URL.

Here is a shortened code example;

$rules['catalog/(.*)/?'] = 'index.php?pagename=catalog&tl=$matches[1]';
array_push($query_vars, 'tl'); // note query var should match your query string

This would map catalog/whatever to the WordPress page 'catalog', and pass along the query var 'tl'. You could create a page template for 'catalog', then pick up the value of 'tl' using get_query_var('tl').

Also avoid using query vars like id - use something more unique (like 'tl') to avoid clashes with WordPress.

And don't flush rules on every init! It's bad practice, and will write to .htaccess and call database updates on every page load!

WordPress will always flush permalinks whenever you update a post or your permalink structure (simply update your permalinks when you make changes to your code).

TheDeadMedic
@TheDeadMedic, would it be possible to redirect to a child page? I have put the postname into pagename, but it's actually redirecting the page.
Jason McCreary
If it's a child page, `pagename` should be the slug **path** - for example `pagename=parentname/childname`
TheDeadMedic
A: 

This article over at Raazorlight goes into a bit more detail on the process of grabbing querystrings and URL rewriting in WP.

Also, check the comments there to see why calling flushRules() may not be necessary if you re-save permalinks. Optionally, flushRules() can be called just once during plugin activation callback.

Digging deeper, commenter 'pmdci' links over to an instructive post/saga on the related topic of passing a query to a custom post type using a custom taxonomy.