I have a product loop in a certain page,
and I want to filter its categories via URL such as:

mysite.com/products // Shows all products
mysite.com/products/sculptures // Shows only sculptures
mysite.com/products/sculptures/2 // Shows only sculptures paged 2
mysite.com/products/paintings // Shows only paintings

So I am trying to map like this:

mysite.com/products/{category}/{paged} // Shows only sculptures

But this hasn't worked so far. By the way, my code also works as shortcode.

1 Answer 1


Try this code:

add_filter( 'query_vars', 'my_query_vars' );
function my_query_vars( $vars ) {
    $vars[] = 'catname';
    return $vars;

add_action( 'generate_rewrite_rules', 'my_rewrite_rules' );
function my_rewrite_rules( $wp_rewrite )
    $products_page_id = 1; //your product's page ID
    $wp_rewrite->rules = array(
        'products/?([0-9]{1,})/?$' => $wp_rewrite->index . '?page_id='.$products_page_id.'&paged=' . $wp_rewrite->preg_index( 1 ),
        'products/(.+?)/?([0-9]{1,})/?$' => $wp_rewrite->index . '?page_id='.$products_page_id.'&catname='.$wp_rewrite->preg_index( 1 ).'&paged=' . $wp_rewrite->preg_index( 2 ),
        'products/(.+?)/?$' => $wp_rewrite->index . '?page_id='.$products_page_id.'&catname='.$wp_rewrite->preg_index( 1 ),
    ) + $wp_rewrite->rules;

You'll get cat_name than as get_query_var('catname'); and paged as get_query_var('paged');

To little explain the code above: this adds rewrite rules to WordPress, when each request to www.yourdomain.com/products/ get rewrote to (means brings content from) www.yourdomain.com/index.php?page_id={$products_page_id}&paged=2 (for example).

$producst_page_id is a ID of your products page in administration with your shorcode - thus page which content should appear. paged is a parameter for you to be able to get another page of your products. catname is another param for you to, filter returned products by category.

  • Thank you, but it seems the page name must be "static", right? How can I make it dynamic?
    – Digerkam
    Feb 5, 2013 at 12:20
  • I'v modified the code to use with page_id instead of pagename Feb 5, 2013 at 12:20
  • @david-binda Then we still need to put "products" into rewrite rules?
    – Digerkam
    Feb 5, 2013 at 12:23
  • yes, you have... Feb 5, 2013 at 12:33
  • @david-binda I see, then what does "products_page_id" work for?
    – Digerkam
    Feb 5, 2013 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.