1

I'm trying to pass custom url parameters to pretty urls using

add_rewrite_tag('%product%', '([0-9/]+)');
add_rewrite_rule('^sign-up/product/([0-9/]+)?$','index.php?pagename=sign-up&product=$matches[2]','top');

and while I can go to /sign-up/product/60/ successfully

the $wp_query->query_var['product'] variable seems to be empty

I'm not sure what I am doing wrong...is there anything else I need to do again? I've flushed the rules several times just to be sure but no dice.

1 Answer 1

3

You only have one capture group, the ID is in matches[1], there is no matches[2].

EDIT-

Here is the working version I tested in the 2016 theme. I created a page with slug sign-up, added the following to functions.php, then visited the Permalinks Settings page to flush rewrite rules. The value passed to product is available in the template via get_query_var( 'product' );

function wpd_product_rewrite() {
    add_rewrite_tag( '%product%', '([0-9/]+)' );
    add_rewrite_rule(
        '^sign-up/product/([0-9/]+)?$',
        'index.php?pagename=sign-up&product=$matches[1]',
        'top'
    );
}
add_action( 'init', 'wpd_product_rewrite' );
3
  • Hmmmm....I HAD actually tried that first and I kept getting 404. When I tried the [2] I got the page and the variable but the value is just empty. ....wierd. Is there anything else I should check on?( Yes I flush the cache/ rules regularly)
    – Kendall
    Commented Jan 26, 2016 at 2:49
  • 2
    See edit above. I've tested it and it's working as expected. Make sure your page is a root page and doesn't have a parent assigned. If the page is a child of another page, then pagename must reflect the parent/child slug path. Also verify that product is unique, there is no other plugin or code that's using the product query var for other purposes (like Woocommerce, for example).
    – Milo
    Commented Jan 26, 2016 at 18:40
  • @Milo I lost HOURS of my life lost to trying to figure out why my rewrite rule/tag was not working, and I finally found your comment about making sure the page does not have a parent assigned (or adding the full path to ?pagename if it does). Such a crucial piece of information, THANK YOU!
    – Michael
    Commented Jul 27, 2023 at 19:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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