• Jason Adams

    (@jason_the_adams)


    Greetings!

    So.. I’m trying to do something that’s strange and probably ill advised. I have a custom post type, product, and I’m trying to add another method of reaching the product single page. Here’s what I’ve got:

    `
    function add_product_buy_rewrite($wp_rewrite) {
    $wp_rewrite->rules[‘([^/]+)/buy/?$’]= ‘index.php?product=$matches[1]’;
    return $wp_rewrite;
    }
    `

    The structure would be /product-name/buy. Presently there’s really three pages:

    1. The single: /product/product-name
    2. The archive: /product/
    3. The Overview: /product-name/

    The overview is a page that provides information, faq, etc. for the product. The product single is the page wherein the user can add it to their cart. The goal is to make /product-name/buy the single product page, and canonize the new url to avoid seo issues.

    Unfortunately, the code above does not work. I can see the rule in the rules, but when I attempt to go to a page using that url, I get a 404. Admittedly I’m pretty new to rewrites, and it’s a bit of a black magic, so any direction/advice on this would be greatly appreciated.

    Thanks!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter Jason Adams

    (@jason_the_adams)

    Sorry, I put extra ticks (github) and didn’t include the action:

    add_action('generate_rewrite_rules', 'add_product_buy_rewrite');
    function add_product_buy_rewrite($wp_rewrite) {
      $wp_rewrite->rules['([^/]+)/buy/?$']= 'index.php?product=$matches[1]';
      return $wp_rewrite;
    }

    Thread Starter Jason Adams

    (@jason_the_adams)

    So I was able to get it working with this:
    add_rewrite_rule('^([^/]+)/buy/?$', 'index.php?product=$matches[1]', 'top');

    Cool! My question from here is: What’s the best way to use this as the permalink for the single product page over the old one?

    Thread Starter Jason Adams

    (@jason_the_adams)

    In case someone else finds this (or things I went about this wrong way), I ended up changing the permalink by intercepting and changing it:

    // Add /product-name/buy rewrite
    add_rewrite_rule('^([^/]+)/buy/?$',  'index.php?product=$matches[1]', 'top');
    
    // Replace /product/product-name with new url
    add_filter('post_type_link', 'change_single_product_permalink', 10, 2);
    function change_single_product_permalink($url, $post) {
      if ( POST_PRODUCT != $post->post_type )
        return $url;
    
      $pattern = '/\/' . POST_PRODUCT . '\/([^\/]+)(\/?)$/';
      $replace = '/$1/buy$2';
    
      return preg_replace($pattern, $replace, $url);
    }
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Rewrite a suffixed url’ is closed to new replies.