0

I have a CPT called presskit, and I need to add a custom query var named welcome_box. I have this code right now:

function my_new_url_querystring(){
    add_rewrite_tag( '%welcome_box%','([^&]+)' );

    add_rewrite_rule(
        'presskit/(.?.+?)/box/(.+)/?$',
        'index.php?post_type=presskit&pagename=$matches[1]&welcome_box=$matches[2]',
        'top'
    );

}
add_action( 'init', 'my_new_url_querystring' );

When I try to open mysite.com/presskit/presskit-name/box/john-doe, it gets back to mysite.com/presskit/presskit-name/.

If I open mysite.com/presskit/presskit-name/?welcome_box=john-doe, It works and I can get the query var.

What am I doing wrong? I'm not good with regexes, so maybe the erros is there.

Any tips are welcome!

Update

Thanks to the @Milo answer, I could make it work. Here's the working code:

function my_new_url_querystring(){
    add_rewrite_tag( '%welcome_box%','([^&]+)' );

    add_rewrite_rule(
        'presskit/([^/]+)/message-to/(.*)?/?$',
        'index.php?presskit=$matches[1]&welcome_box=$matches[2]',
        'top'
    );

}
add_action( 'init', 'my_new_url_querystring' );
0

pagename is for the page post type, if you are trying to pass the slug for the presskit post type, remove post_type and pagename and just set presskit=$matches[1] instead.

3
  • Thanks for the info, Milo! What I'm trying to do is get the presskit post as usual, but add the string box/john-doe at the end, allowing this way to get the query var box as john-doe. I updated the rules with our tip, but it doesn't work yet, it redirects to a page with the Hello World post. – Diego de Oliveira Jun 30 '15 at 16:25
  • did you flush rewrite rules? it's probably easier for your purposes to just use add_rewrite_endpoint, it generates the correct rules for you. – Milo Jun 30 '15 at 16:27
  • This is a great tip! add_rewrite_endpoint works, but adds it to all post types, while I just want to add for my presskit CPT. Turns out that you were right, and I had a typo with my rewrite rules. I'll update the code with the right rewrite rule. Thanks! – Diego de Oliveira Jun 30 '15 at 16:40

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.