[wp-hackers] Permalinks Update Hook

Rob Miller r at robm.me.uk
Mon Jun 5 17:04:09 GMT 2006


Mr.Brown wrote:
> Rob Miller <r at robm.me.uk> wrote:
>
>> If you filter rewrite_rules_array don't they automatically get
>> added/updated when the user updates their permalinks?
>
> No, I don't filter the rewrite rules, because I don't yet understand
> how they work.
> I've posted an help request in this list some months ago, I've read
> the Codex examples but I' dont' resolved :-)
>
> Now I'm using this function to make WP use .htaccess the old way also
> with 2.0.x versions.
>
> function GYO_verbose_rewrite() { // thanks to Ryan Boren ;-)
>     global $wp_rewrite;
>     $wp_rewrite->use_verbose_rules = true;
> }
>
> add_action('init', 'GYO_verbose_rewrite');
>
This is how I do it:

First, add some WP_Rewrite variables:

/**
 * Registers our query vars so we can redirect to the library and book 
permalinks.
 * @param array $vars The existing array of query vars
 * @return array The modified array of query vars with our additions.
 */
function nr_query_vars( $vars ) {
    $vars[] = 'now_reading_library';
    return $vars;
}
add_filter('query_vars', 'nr_query_vars');

Then add our rewrite rules:

/**
 * Adds our rewrite rules for the library and book permalinks to the 
regular WordPress ones.
 * @param array $rules The existing array of rewrite rules we're filtering
 * @return array The modified rewrite rules with our additions.
 */
function nr_mod_rewrite( $rules ) {
    global $wp_rewrite;
    $rules['library/?$'] = 'index.php?now_reading_library=true';
    return $rules;
}
add_filter('rewrite_rules_array', 'nr_mod_rewrite');

Now we can check on `init`/`template_redirect` to see if our rewrite 
variables are set and load the appropriate templates:

/**
 * Checks to see if the library/book permalink query vars are set and, 
if so, loads the appropriate templates.
 */
function library_init() {
    global $wp, $wpdb, $q, $query;
   
    $wp->parse_request();
   
    if( $wp->query_vars['now_reading_library'] ) {
        // Library page:
        load_template(dirname(__FILE__).'/templates/library.php');
        die;
    } else
        return;
}
add_action('template_redirect', 'library_init');

(Sorry for the rather verbose examples, btw)

It's pretty complex but fairly intuitive.

Incidentally, does anyone (David?) know what's happening about the 
WP_Rewrite API as discussed here[1]?

[1]: http://trac.wordpress.org/ticket/2433

-- 
Rob Miller
http://robm.me.uk/ | http://kantian.co.uk/



More information about the wp-hackers mailing list