0

I'm trying to create a product compare feature where we can compare three products, Two products must be added while the third is optional.

Trying to use the add_rewrite_rule to create a friendly URL for the product compare page. For example, Something similar to this https://hostadvice.com/tools/web-hosting-comparison/godaddy-vs-hostinger/

To make it work, The following is the what i tried so far, I know this is not the correct one.

add_rewrite_rule( 
    'compare/([^-vs-]*)(?:-vs-)([^-vs-]*)(?:-vs-)([^/]*)?/?',
    'index.php?pagename=compare&compare=$matches[1],$matches[2],$matches[3]',
    'top'
);

desired url structure:

example.com/compare/product1-vs-product2-vs-product3

While the product3 can be optional

It'd be really helpful if someone can correct me on how to make the regex expression work correctly.

Thank you.

0

Here you go:

compare\/([^-vs-]*)(?:-vs-)([^-vs-]*)(?:-vs-)?([^-vs-]*)?

Remember to escape backslashes (as I have done). I also made your lookups more consistent in their internal logic/structure.

I assumed you wouldn't want a second -vs- if the third product wasn't there, so this is why you now have the second non-capturing group.

Here is a link with the answer in regex: https://regexr.com/3u465 to make things clear. Please let me know if I misunderstood your requirements. :)

  • Thanks for answering, but the problem I'm facing is, if the product name contain any character from -vs- then it escapes whole product name, for example check this link here the 2nd product has v in its name. – curious_curious Aug 18 '18 at 5:28

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.