1

I'm trying to flush rewrite rules in a plugin and it isn't working. I have to go to permalinks -> save in the admin panel for the rewrites to flush. Can anyone see why?

class SpektrixPlugin {

public function __construct(){
    add_filter('query_vars', array($this, 'add_query_vars'));
    add_action('init', array($this, 'add_rewrite_rules'));
}

public function activate() {

    flush_rewrite_rules();
}

public function deactivate() {

    flush_rewrite_rules();
}

public function add_query_vars($vars) {
    $vars[] = "event"; // name of the var as seen in the URL
    return $vars;
}

public function add_rewrite_rules() {
    $page = get_page_by_title( 'Event' );
    add_rewrite_rule( 'whats-on/(.+)/?$' , 'index.php?page_id='.$page->ID.'&event=$matches[1]' , 'top' );
}


}

$SpektrixEvents = new SpektrixPlugin;

register_activation_hook( __FILE__, array($SpektrixEvents, 'activate') );
register_deactivation_hook( __FILE__, array($SpektrixEvents, 'deactivate') );
4

Before flashing rules you have to add them:

public function activate() {
  $this->add_rewrite_rules();
  flush_rewrite_rules();
}
|improve this answer|||||
  • Is this aplly also for the deactivation hook? – cybmeta Sep 6 '13 at 10:32
  • @cybnet no. On deactivation just flush, because once the plugin is not active not rule is added on init. – gmazzap Sep 6 '13 at 12:15
  • Mmmm....I've been trying several times to deactivate my plugin, running flush_rewrite_rules(); on deactivation hook but the rewrite analyzer still displays my custom rewrite rules after the deactivation. Only flusing in settings->permalinks make disappear them (including the rewrite rules added by Wordpress in the custom taxonomy registration by the plugin). – cybmeta Sep 6 '13 at 12:26
  • If I visit a url handled by the plugin after the deactivation I get my home page without a 404 code in the http headers. Only after I manually flush the rewrite rules I will get the 404 error, which is the correct http status code if the plugin is not active. So, it is important to flush the rewrite rules when the plugin is deactivated. And it is should be done automatically in the deactivation hook. Should I start a new question for this? – cybmeta Sep 6 '13 at 13:52
  • I know they can be flushed manually but is not the point. Also, you prefer not get 404 error, but preferences are also not the point. If a page dosen't exists the server must return a 404 status code, it is not teorically correct, it is the standard in web applications. – cybmeta Sep 6 '13 at 14:13

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.