I created a page template that gets products by brand ID using a query string in the URL like so: https://example.com/all-products/?brand={brand_id}

Due to a request, the URL needs to read https://example.com/catalog/brand/{brand_name}

I've been looking at the Codex for URL Rewrites but am not having any luck. I'm thinking that the problem lies in the second parameter of my rewrite rule.

function custom_rewrite_basic() {
  add_rewrite_tag('%brand%', '([^&]+)');
  add_rewrite_rule('^catalog/brand/([^/]*)/?', 'index.php?page_id=19563&brand=$matches[1]', 'top'); 
  page_id=19563&brand=$matches[1]', 'top');
add_action('init', 'custom_rewrite_basic', 10, 0);

So in this case, the page_id is the ID of the all-products page... Is that right?

Something else that should be mentioned is that this page also includes pagination. Wouldn't that also need to be accounted for in the rewrite?

  • I'd advise against hard coding the page ID, if you really must, hardcode a page slug otherwise everything will break if you ever migrate the site or accidentlly delete/recreate the page – Tom J Nowell Feb 15 at 18:34
  • As an aside, is there a particular reason you don't have a taxonomy named brand with terms such as "gucci" or "insert brand name here"? If you had, there'd be a taxonomy-brand.php` template and a post archive just for that brand which you could change the URL of when you register the taxonomy. You'd literally get everything you wanted for free, and it would work without needing to set up a page template – Tom J Nowell Feb 15 at 18:36
  • @Tom J Nowell Brand is a custom post type using an ACF relationship field for the products to brand relationship. This site was inherited from another team. – Jake Stewart Feb 15 at 18:53
  • oh dear, so nobody ever created a brand taxonomy? Could you not write a quick WP CLI command to convert the data? That'd save a lot of time, and actually improve performance signficantly ( searching for posts by their post meta is sloooooow, filtering by taxonomy on the other hand is fast ) – Tom J Nowell Feb 15 at 19:01
  • That approach would make a lot more sense. I'll try it and see what happens. – Jake Stewart Feb 15 at 20:04

Your Answer

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

Browse other questions tagged or ask your own question.