add_rewrite_rule wordpress with w3 total cache

2019-06-08 21:47发布

问题:

I am trying to rewrite rule to seo friendly. Here is the code I put in my theme function.php

add_action('init', 'add_my_rewrite_rule');
function add_my_rewrite_rule(){
    add_rewrite_rule('^quiz/([^/]*)/([^/]*)?','index.php?pagename=quiz&quiztitle=$matches[1]&quizid=$matches[2]','top');
}

add_filter('query_vars','set_quiz_query_var');
  function set_quiz_query_var($vars) {
  array_push($vars, 'quiztitle');
  array_push($vars, 'quizid');
  return $vars;
}

Because this snippet didn't work, I also tried to rewrite .htaccess rule.

RewriteRule ^quiz/([^/]+)/([^/]+)$ /index.php?pagename=quiz&quiztitle=$1&quizid=$2 [NC,R=301,L]

I guess this is because of w3 total cache. I spent whole night but couldn't figure it out alone....

回答1:

flush the rewrite rules -- go to settings permalinks and click on "save"



回答2:

Sorry for answering myself! I spent whole night and day to find out the issue.

I used add_filter instead of add_action and it worked out.

add_filter('rewrite_rules_array','add_my_rewrite_rule');
function add_my_rewrite_rule($rules)
{
  $newrules = array();
  $newrules['^quiz/([^/]+)/([^/]+)/?'] = 'index.php?pagename=quiz&quiztitle=$matches[1]&quizid=$matches[2]';
  return $newrules + $rules;
}