[wp-hackers] Make WP_Rewrite eaiser to use

David House dmhouse at gmail.com
Sun Feb 5 15:36:09 GMT 2006


Reading through the recent thread concerning Scott Merril's troubles
with WP_Rewrite [1], I thought that we really should automate a lot of
what is in the final plugin [2]. People (well, Owen) have been asking
for a while that WP_Rewrite should be easier to use. I'm not proposing
a full rewrite of WP_Rewrite, but I do think we should provide more
API to help the mortal plugin authors understand it.

For example, here's my proposal for a couple of functions that should
make interacting with WP_Rewrite easier (if there's no disagreement
with the specification then I'll draft up some patches):

----------------------------------------------------------------------------
1. add_rewrite_rule(): A function for adding a straight rewrite rule.

Parameters:
* Regex to match
* URL to redirect to.

What it needs to do:
* Build a rewrite rule from the regex and redirect URL.
* Theoretically it could then filter rewrite_rules_array and add the
rules itself, but I think we should add a function to WP_Rewrite for
adding 'extra' rules that needn't be generated by
generate_rewrite_rules(). rewrite_rules() would then just tack on
these extra rules after the ones generated. These extra rules should
probably be stored in an option.

----------------------------------------------------------------------------
2. add_rewrite_tag(): Add a new tag (like %postname%):

Parameters:
* Name of tag
* Regex to match

What it needs to do:
* Get a query var name by stripping the % signs from the name of the
tag: trim($name, '%')
* Call $wp_rewrite->add_rewrite_tag() with the name, generated QV name
and regex.
* Add the QV as a query var (again, this could be done by filtering
query_vars but it might be nicer to add a function to the WP class
that stores 'extra' QVs like above)

Notes:
I was thinking about passing a callback to this function which would
be called with the contents of the QV when a request matched the regex
(so e.g. if the regex is ([0-9]{3}) as in skippy's case, we could
accept a callback to call when someone requests a Julian date, say,
/2006/32, passing 32), but I don't think this will be flexible enough:
people might want to hook onto parse_request, or pre_get_posts, or
parse_query, or many other hooks. So we can just do the
$wp_rewrite->add_rewrite_tag() bit and leave it up to the query author
to add their own hooks.

----------------------------------------------------------------------------

Examples:

To do something similar to what skippy was asking for, you'd do this:

http://xmouse.ithium.net/dmh-source/wp-rewrite-api.phps

[1]: http://comox.textdrive.com/pipermail/wp-hackers/2006-February/004511.html
[2]: http://www.skippy.net/secret/dayofyear.phps
--
-David House, dmhouse at gmail.com, http://xmouse.ithium.net


More information about the wp-hackers mailing list