Forums

Correct usage of add_rewrite in plugin (3 posts)

  1. bennybobw
    Member
    Posted 11 months ago #

    Following this post
    http://wordpress.org/support/topic/208830?replies=6
    I came up with this code:

    function wftp_rewrite() {
      global $wp_rewrite;
      $wp_rewrite->flush_rules();
      add_rewrite_rule('wftp/([^/]+)/?$', 'index.php?wftp=$matches[1]','top');
    }
    function wftp_vars($public_query_vars) {
        $public_query_vars[] = 'wftp';
        return $public_query_vars;
    }
    add_filter('query_vars', 'wftp_vars');
    add_action('init', 'wftp_rewrite');

    But that doesn't work. However, based on this post http://codex.wordpress.org/Custom_Queries, the following does work:

    function wftp_flush_rewrite() {
      global $wp_rewrite;
      $wp_rewrite->flush_rules();
    }
    function wftp_vars($public_query_vars) {
        $public_query_vars[] = 'wftp';
        return $public_query_vars;
    }
    function wftp_add_rewrite_rules($wp_rewrite) {
      $new_rules = array(
         'wftp/(.+)' => 'index.php?wftp=' .
           $wp_rewrite->preg_index(1));
      $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
    }
    add_action('init', 'wftp_flush_rewrite');
    add_filter('query_vars', 'wftp_vars');
    add_action('generate_rewrite_rules', 'wftp_add_rewrite_rules');
    add_action('parse_query', 'wftp_init');

    Can anyone explain to me why I can't use add_rewrite_rule in this way, since it seems like it works in this post:
    http://danmarvelo.us/older/2007/5/30/custom-rewrite-wordpress-add_rewrite_rule-add_rewrite_tag/

    I don't understand why I have to add directly to $wp_rewrite...
    Thanks for your help!

  2. filosofo
    Member
    Posted 11 months ago #

    First of all, don't flush your rewrite rules every time you initialize WordPress---that's some seriously unnecessary server resources being eaten up. Just flush when you activate the plugin or otherwise make changes to the rewrite rules.

    Second, the problem is that add_rewrite_rule needs to come before you flush the rules. I know it seems unintuitive, but what happens when you flush the rules is that they're immediately regenerated, at which point WordPress says, "hmm, what rewrite rules do I need to include?" It doesn't see yours yet, because add_rewrite_rule hasn't yet been called, so it regenerates the rules without it.

    So use wftp_rewrite() as in the first example, but call $wp_rewrite->flush_rules() last and only call wftp_rewrite() when options have been saved or the plugin is first activated.

  3. wbeeler
    Member
    Posted 10 months ago #

    Hey bennybob. Can you supply the whole rewrite file for others to see. I'm having some trouble understanding the whole thing myself, so it would be really nice to see what others have done, so I can learn from that. I appreciate it man.

Reply

You must log in to post.

About this Topic