[wp-hackers] Best practice way for a plugin to use WP_Rewrite

Peter Westwood peter.westwood at ftwr.co.uk
Fri Nov 13 09:25:49 UTC 2009


On 13 Nov 2009, at 03:38, Tuna Can wrote:

> Honestly, I would be ecstatic to be proven wrong on this. Do you  
> have any idea why using a plugin with only the following code (plus  
> the required plugin header of course):
>
> function my_flush_rewrites() {
> 	global $wp_rewrite;
> 	$wp_rewrite->flush_rules();
> }
>
> function my_add_rewrites() {
> 	global $wp_rewrite;
> 	$my_new_non_wp_rules = array(
> 		'this/([0-9]+)$' => 'that/index.php?a=$1',
> 	);
> 	$wp_rewrite->non_wp_rules = $my_new_non_wp_rules + $wp_rewrite- 
> >non_wp_rules;
> }
>
> add_action( 'generate_rewrite_rules', 'my_add_rewrites' );
> add_action( 'admin_init', 'my_flush_rewrites' );
>
> ...will automatically write the following in .htaccess:
>
> RewriteRule ^this/([0-9]+)$ /that/index.php?a=$1 [QSA,L]
>
> ...but, if I set the .htaccess back to the WP default, then change  
> the 'admin_init' to just 'init' like so:
>
> add_action( 'init', 'my_flush_rewrites' );
>
> ...the changes aren't written to .htaccess unless I go to Settings /  
> Permalinks and "Save Changes" manually?

Because the function save_mod_rewrite_rules() is only defined for  
admin pages. (It is in wp-admin/includes/misc.php)
and WP_Rewrite uses that to save to the .htaccess file

You really don't want to flush the rules on every page load anyway.

Peter
-- 
Peter Westwood
http://blog.ftwr.co.uk | http://westi.wordpress.com
C53C F8FC 8796 8508 88D6 C950 54F4 5DCD A834 01C5



More information about the wp-hackers mailing list