I am having trouble getting WordPress to assign the proper values to variables using the add_rewrite_rule() function. My goal is to have a url that looks like this: www.mywebsite.com/catalog/category1/category2/item-slug.
Here is my code from the functions.php file:
add_filter( 'query_vars', 'query_vars_new' );
function query_vars_new($query_vars){
$query_vars[]='category1';
$query_vars[]='category2';
$query_vars[]='catalog_item';
return $query_vars;
}
add_action( 'init', 'rewrite_init' );
function rewrite_init(){
add_rewrite_rule('catalog(/([^/]+))?(/([^/]+))?/?','index.php?page_id=94&category1=$matches[1]&category2=$matches[2]&catalog_item=$matches[3]','top');
}
So the goal is to have three variables $category1, $category2, and $catalog_item with the values from the corresponding url segments. However, when I test this the first two variables are set to the same value.
For example, www.mywebsite.com/catalog/clothes/shirts/polo-shirt should return:
$category1="clothes";
$category2="shirts";
$catalog_item="polo-shirt";
But instead I get:
$category1="/clothes";
$category2="clothes";
$catalog_item="/polo-shirt";
There must be something wrong with my add_rewrite_rule function, but I can’t figure it out.
Thanks to the incredibly underwhelming response to this question I ended up just making it work without the help of the WordPress variables. I just configured WordPress to allow the variables in the url, then used PHP to fetch the URL and get the different URL segments and analyze them. Not quite as pretty as the WordPress method, but at least it works.