0

I have to rewrite the product's permalink by changing it from the default /product/product-name into /%product-cat%/product-name. %product-cat% is a custom category. But after I rewrite it, the pagination for product review is not working. Not matter what page I click, the url is correct but the reviews are always stuck at first page. This is my first attempt on doing a permalink rewrite. Did I missed out anything or added wrong line of code thus causing the pagination query to fail?

Below is the rewrite code that I have attempt:

function product_perma_Rewrite() {

    $prodCat = ['taxonomy' => 'product_cat'];
    $categories = get_categories($prodCat);
    $catSlug = [];
    foreach($categories as $category) {
        $catSlug[] = $category->slug;
    }
    add_rewrite_rule(
        '^('.implode('|', $catSlug).')/([^/]*)/?',
        'index.php?post_type=product&category=$matches[1]&product=$matches[2]',
        'top'
    );
    flush_rewrite_rules();
}
add_action('init', 'product_perma_Rewrite');
2
  • There is no pagination rule, how will WP pick up that it's page 2 or pass 2 etc into the query string? Take a look at the post and page rewrite rules, they have checks on the end for pagination and query variables that your rule doesn't have. Also, flushing rewrite rules on init can be extremely expensive and cause bugs. It should be enough just to visit the permalinks settings page without saving to flush rules – Tom J Nowell Mar 1 at 11:53
  • Thanks @TomJNowell !! – Amy Mar 5 at 3:06
0

I managed to get it fixed with the advice from tom. This is the solution I tried.

function product_perma_Rewrite() {

    $prodCat = ['taxonomy' => 'product_cat'];
    $categories = get_categories($prodCat);
    $catSlug = [];
    foreach($categories as $category) {
        $catSlug[] = $category->slug;
    }
    
     add_rewrite_rule(
        '^('.implode('|', $catSlug).')/([^/]+)/comment-page-([0-9]{1,})/?$',
        'index.php?post_type=product&category=$matches[1]&product=$matches[2]&cpage=$matches[3]','top'
    );
    
    add_rewrite_rule(
        '^('.implode('|', $catSlug).')/([^/]*)/?',
        'index.php?post_type=product&category=$matches[1]&product=$matches[2]',
        'top'
    );
    
    flush_rewrite_rules();
}
add_action('init', 'product_perma_Rewrite');

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.