0

I am trying to use add_rewrite_rule() to solve a pagination problem I am having. After a lot of research I know the answer. But it seems the second argument of add_rewrite_rule() is never working.

add_action( 'init', 'add_category_base_rewrite_rule' );
function add_category_base_rewrite_rule() {
  add_rewrite_rule(
    'publicacoes/(.+?)/page/?([0-9]{1,})/?$',
    'index.php?post_type=artigo&category_name=$matches[1]&paged=$matches[2]',
    'top' 
  );
}

I am using the plugin Debug This to check the rewrite rules

enter image description here

As you can see the second argument doesn't match what I put in my function. And no matter what I do it doesn't work.

I know the function is being called because it put my rule on the top.

What I am doing wrong?

  • 1
    did you flush rewrite rules after making changes? – Milo May 5 '18 at 15:37
  • Yes I did. I put flush_rewrite_rules(true); right before my code in functions php. And tried to do it manually as well. Didn't work – Colen_br May 5 '18 at 16:49
  • When you call flush_rewrite_rules, rules get rebuilt from whatever is currently added in that request, so you must add_rewrite_rule before a flush. – Milo May 5 '18 at 17:38
  • I tried this.... What happens is that I can see the rule going up in the list, probably because of the 'top' parameter. But the rewrite still doesn't change. Am I missing something? – Colen_br May 6 '18 at 11:00
1

on the rewrite flush, the rewrite rule created by the custom post type overwrite yours because the target is the same.

to avoid this, you can use this filter

const TAXONOMY_PUBLICACOES = "publicacoes";

add_filter(TAXONOMY_PUBLICACOES . "_rewrite_rules", function ($rules) {

    unset($rules["publicacoes/(.+?)/page/?([0-9]{1,})/?$"]);

    return $rules;

});
  • I tried putting this code before and after 'add_rewrite_rule'. What I noticed is the rule going up in the rules' list. But the rewrite value still doesn't change. Am I missing someting in the 'add_rewrite_rule' ? – Colen_br May 6 '18 at 11:01
  • I am not even sure if this filter is being called. I tried to echo something inside the function to test, but I couldn't see the return. – Colen_br May 6 '18 at 11:08
  • I manage to call the filter, using apply_filters. But when I var_dump($rules) inside the filter, it is returning NULL. – Colen_br May 6 '18 at 11:21
  • 1
    The filter doesn’t run on every request, only when rules are flushed and rebuilt. – Milo May 6 '18 at 21:29
  • Got it... But it still didn't work =/.... I can see the rule go up in the list. But the rewrite value doesn't update. Any other thoughts? – Colen_br May 7 '18 at 23:53

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.