4 *******************************************************************************/
6 //Add a straight rewrite rule
7 function add_rewrite_rule($regex, $redirect, $after = 'bottom') {
9 $wp_rewrite->add_rule($regex, $redirect, $after);
12 //Add a new tag (like %postname%)
13 //warning: you must call this on init or earlier, otherwise the query var addition stuff won't work
14 function add_rewrite_tag($tagname, $regex) {
16 if (strlen($tagname) < 3 || $tagname{0} != '%' || $tagname{strlen($tagname)-1} != '%') {
20 $qv = trim($tagname, '%');
22 global $wp_rewrite, $wp;
23 $wp->add_query_var($qv);
24 $wp_rewrite->add_rewrite_tag($tagname, $regex, $qv . '=');
27 //Add a new feed type like /atom1/
28 function add_feed($feedname, $function) {
30 if (!in_array($feedname, $wp_rewrite->feeds)) { //override the file if it is
31 $wp_rewrite->feeds[] = $feedname;
33 $hook = 'do_feed_' . $feedname;
34 remove_action($hook, $function, 10, 1);
35 add_action($hook, $function, 10, 1);
39 define('EP_PERMALINK', 1 );
40 define('EP_ATTACHMENT', 2 );
41 define('EP_DATE', 4 );
42 define('EP_YEAR', 8 );
43 define('EP_MONTH', 16 );
44 define('EP_DAY', 32 );
45 define('EP_ROOT', 64 );
46 define('EP_COMMENTS', 128 );
47 define('EP_SEARCH', 256 );
48 define('EP_CATEGORIES', 512 );
49 define('EP_TAGS', 1024 );
50 define('EP_AUTHORS', 2048);
51 define('EP_PAGES', 4096);
53 define('EP_NONE', 0 );
54 define('EP_ALL', 8191);
56 //and an endpoint, like /trackback/
57 function add_rewrite_endpoint($name, $places) {
59 $wp_rewrite->add_endpoint($name, $places);
62 // examine a url (supposedly from this blog) and try to
63 // determine the post ID it represents.
64 function url_to_postid($url) {
67 $url = apply_filters('url_to_postid', $url);
69 // First, check to see if there is a 'p=N' or 'page_id=N' to match against
70 if ( preg_match('#[?&](p|page_id|attachment_id)=(\d+)#', $url, $values) ) {
71 $id = absint($values[2]);
76 // Check to see if we are using rewrite rules
77 $rewrite = $wp_rewrite->wp_rewrite_rules();
79 // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
80 if ( empty($rewrite) )
83 // $url cleanup by Mark Jaquith
84 // This fixes things like #anchors, ?query=strings, missing 'www.',
85 // added 'www.', or added 'index.php/' that will mess up our WP_Query
86 // and return a false negative
88 // Get rid of the #anchor
89 $url_split = explode('#', $url);
92 // Get rid of URL ?query=string
93 $url_split = explode('?', $url);
96 // Add 'www.' if it is absent and should be there
97 if ( false !== strpos(get_option('home'), '://www.') && false === strpos($url, '://www.') )
98 $url = str_replace('://', '://www.', $url);
100 // Strip 'www.' if it is present and shouldn't be
101 if ( false === strpos(get_option('home'), '://www.') )
102 $url = str_replace('://www.', '://', $url);
104 // Strip 'index.php/' if we're not using path info permalinks
105 if ( !$wp_rewrite->using_index_permalinks() )
106 $url = str_replace('index.php/', '', $url);
108 if ( false !== strpos($url, get_option('home')) ) {
109 // Chop off http://domain.com
110 $url = str_replace(get_option('home'), '', $url);
112 // Chop off /path/to/blog
113 $home_path = parse_url(get_option('home'));
114 $home_path = $home_path['path'];
115 $url = str_replace($home_path, '', $url);
118 // Trim leading and lagging slashes
119 $url = trim($url, '/');
126 $request_match = $request;
127 foreach ($rewrite as $match => $query) {
128 // If the requesting file is the anchor of the match, prepend it
130 if ( (! empty($url)) && (strpos($match, $url) === 0) && ($url != $request)) {
131 $request_match = $url . '/' . $request;
134 if ( preg_match("!^$match!", $request_match, $matches) ) {
136 // Trim the query of everything up to the '?'.
137 $query = preg_replace("!^.+\?!", '', $query);
139 // Substitute the substring matches into the query.
140 eval("\$query = \"$query\";");
141 // Filter out non-public query vars
143 parse_str($query, $query_vars);
145 foreach ( $query_vars as $key => $value ) {
146 if ( in_array($key, $wp->public_query_vars) )
147 $query[$key] = $value;
150 $query = new WP_Query($query);
151 if ( $query->is_single || $query->is_page )
152 return $query->post->ID;
161 *******************************************************************************/
164 var $permalink_structure;
165 var $use_trailing_slashes;
168 var $category_structure;
170 var $author_base = 'author';
171 var $author_structure;
174 var $search_base = 'search';
175 var $search_structure;
176 var $comments_base = 'comments';
177 var $feed_base = 'feed';
178 var $comments_feed_structure;
182 var $index = 'index.php';
185 var $extra_rules = array(); //those not generated by the class, see add_rewrite_rule()
186 var $extra_rules_top = array(); //those not generated by the class, see add_rewrite_rule()
187 var $non_wp_rules = array(); //rules that don't redirect to WP's index.php
188 var $extra_permastructs = array();
190 var $use_verbose_rules = false;
191 var $use_verbose_page_rules = true;
209 var $rewritereplace =
243 var $feeds = array ( 'feed', 'rdf', 'rss', 'rss2', 'atom' );
245 function using_permalinks() {
246 if (empty($this->permalink_structure))
252 function using_index_permalinks() {
253 if (empty($this->permalink_structure)) {
257 // If the index is not in the permalink, we're using mod_rewrite.
258 if (preg_match('#^/*' . $this->index . '#', $this->permalink_structure)) {
265 function using_mod_rewrite_permalinks() {
266 if ( $this->using_permalinks() && ! $this->using_index_permalinks())
272 function preg_index($number) {
276 if (! empty($this->matches)) {
277 $match_prefix = '$' . $this->matches . '[';
281 return "$match_prefix$number$match_suffix";
284 function page_uri_index() {
287 //get pages in order of hierarchy, i.e. children after parents
288 $posts = get_page_hierarchy($wpdb->get_results("SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'page'"));
289 //now reverse it, because we need parents after children for rewrite rules to work properly
290 $posts = array_reverse($posts, true);
292 $page_uris = array();
293 $page_attachment_uris = array();
296 return array( array(), array() );
299 foreach ($posts as $id => $post) {
301 $uri = get_page_uri($id);
302 $attachments = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'attachment' AND post_parent = %d", $id ));
303 if ( $attachments ) {
304 foreach ( $attachments as $attachment ) {
305 $attach_uri = get_page_uri($attachment->ID);
306 $page_attachment_uris[$attach_uri] = $attachment->ID;
310 $page_uris[$uri] = $id;
313 return array( $page_uris, $page_attachment_uris );
316 function page_rewrite_rules() {
317 $rewrite_rules = array();
318 $page_structure = $this->get_page_permastruct();
320 if ( ! $this->use_verbose_page_rules ) {
321 $this->add_rewrite_tag('%pagename%', "(.+?)", 'pagename=');
322 $rewrite_rules = array_merge($rewrite_rules, $this->generate_rewrite_rules($page_structure, EP_PAGES));
323 return $rewrite_rules;
326 $page_uris = $this->page_uri_index();
327 $uris = $page_uris[0];
328 $attachment_uris = $page_uris[1];
331 if( is_array( $attachment_uris ) ) {
332 foreach ($attachment_uris as $uri => $pagename) {
333 $this->add_rewrite_tag('%pagename%', "($uri)", 'attachment=');
334 $rewrite_rules = array_merge($rewrite_rules, $this->generate_rewrite_rules($page_structure, EP_PAGES));
337 if( is_array( $uris ) ) {
338 foreach ($uris as $uri => $pagename) {
339 $this->add_rewrite_tag('%pagename%', "($uri)", 'pagename=');
340 $rewrite_rules = array_merge($rewrite_rules, $this->generate_rewrite_rules($page_structure, EP_PAGES));
344 return $rewrite_rules;
347 function get_date_permastruct() {
348 if (isset($this->date_structure)) {
349 return $this->date_structure;
352 if (empty($this->permalink_structure)) {
353 $this->date_structure = '';
357 // The date permalink must have year, month, and day separated by slashes.
358 $endians = array('%year%/%monthnum%/%day%', '%day%/%monthnum%/%year%', '%monthnum%/%day%/%year%');
360 $this->date_structure = '';
363 foreach ($endians as $endian) {
364 if (false !== strpos($this->permalink_structure, $endian)) {
365 $date_endian= $endian;
370 if ( empty($date_endian) )
371 $date_endian = '%year%/%monthnum%/%day%';
373 // Do not allow the date tags and %post_id% to overlap in the permalink
374 // structure. If they do, move the date tags to $front/date/.
375 $front = $this->front;
376 preg_match_all('/%.+?%/', $this->permalink_structure, $tokens);
378 foreach ($tokens[0] as $token) {
379 if ( ($token == '%post_id%') && ($tok_index <= 3) ) {
380 $front = $front . 'date/';
386 $this->date_structure = $front . $date_endian;
388 return $this->date_structure;
391 function get_year_permastruct() {
392 $structure = $this->get_date_permastruct($this->permalink_structure);
394 if (empty($structure)) {
398 $structure = str_replace('%monthnum%', '', $structure);
399 $structure = str_replace('%day%', '', $structure);
401 $structure = preg_replace('#/+#', '/', $structure);
406 function get_month_permastruct() {
407 $structure = $this->get_date_permastruct($this->permalink_structure);
409 if (empty($structure)) {
413 $structure = str_replace('%day%', '', $structure);
415 $structure = preg_replace('#/+#', '/', $structure);
420 function get_day_permastruct() {
421 return $this->get_date_permastruct($this->permalink_structure);
424 function get_category_permastruct() {
425 if (isset($this->category_structure)) {
426 return $this->category_structure;
429 if (empty($this->permalink_structure)) {
430 $this->category_structure = '';
434 if (empty($this->category_base))
435 $this->category_structure = $this->front . 'category/';
437 $this->category_structure = $this->category_base . '/';
439 $this->category_structure .= '%category%';
441 return $this->category_structure;
444 function get_tag_permastruct() {
445 if (isset($this->tag_structure)) {
446 return $this->tag_structure;
449 if (empty($this->permalink_structure)) {
450 $this->tag_structure = '';
454 if (empty($this->tag_base))
455 $this->tag_structure = $this->front . 'tag/';
457 $this->tag_structure = $this->tag_base . '/';
459 $this->tag_structure .= '%tag%';
461 return $this->tag_structure;
464 function get_extra_permastruct($name) {
465 if ( isset($this->extra_permastructs[$name]) )
466 return $this->extra_permastructs[$name];
470 function get_author_permastruct() {
471 if (isset($this->author_structure)) {
472 return $this->author_structure;
475 if (empty($this->permalink_structure)) {
476 $this->author_structure = '';
480 $this->author_structure = $this->front . $this->author_base . '/%author%';
482 return $this->author_structure;
485 function get_search_permastruct() {
486 if (isset($this->search_structure)) {
487 return $this->search_structure;
490 if (empty($this->permalink_structure)) {
491 $this->search_structure = '';
495 $this->search_structure = $this->root . $this->search_base . '/%search%';
497 return $this->search_structure;
500 function get_page_permastruct() {
501 if (isset($this->page_structure)) {
502 return $this->page_structure;
505 if (empty($this->permalink_structure)) {
506 $this->page_structure = '';
510 $this->page_structure = $this->root . '%pagename%';
512 return $this->page_structure;
515 function get_feed_permastruct() {
516 if (isset($this->feed_structure)) {
517 return $this->feed_structure;
520 if (empty($this->permalink_structure)) {
521 $this->feed_structure = '';
525 $this->feed_structure = $this->root . $this->feed_base . '/%feed%';
527 return $this->feed_structure;
530 function get_comment_feed_permastruct() {
531 if (isset($this->comment_feed_structure)) {
532 return $this->comment_feed_structure;
535 if (empty($this->permalink_structure)) {
536 $this->comment_feed_structure = '';
540 $this->comment_feed_structure = $this->root . $this->comments_base . '/' . $this->feed_base . '/%feed%';
542 return $this->comment_feed_structure;
545 function add_rewrite_tag($tag, $pattern, $query) {
546 // If the tag already exists, replace the existing pattern and query for
547 // that tag, otherwise add the new tag, pattern, and query to the end of
549 $position = array_search($tag, $this->rewritecode);
550 if (FALSE !== $position && NULL !== $position) {
551 $this->rewritereplace[$position] = $pattern;
552 $this->queryreplace[$position] = $query;
554 $this->rewritecode[] = $tag;
555 $this->rewritereplace[] = $pattern;
556 $this->queryreplace[] = $query;
560 //the main WP_Rewrite function. generate the rules from permalink structure
561 function generate_rewrite_rules($permalink_structure, $ep_mask = EP_NONE, $paged = true, $feed = true, $forcomments = false, $walk_dirs = true, $endpoints = true) {
562 //build a regex to match the feed section of URLs, something like (feed|atom|rss|rss2)/?
564 foreach ($this->feeds as $feed_name) {
565 $feedregex2 .= $feed_name . '|';
567 $feedregex2 = '(' . trim($feedregex2, '|') . ')/?$';
568 //$feedregex is identical but with /feed/ added on as well, so URLs like <permalink>/feed/atom
569 //and <permalink>/atom are both possible
570 $feedregex = $this->feed_base . '/' . $feedregex2;
572 //build a regex to match the trackback and page/xx parts of URLs
573 $trackbackregex = 'trackback/?$';
574 $pageregex = 'page/?([0-9]{1,})/?$';
576 //build up an array of endpoint regexes to append => queries to append
578 $ep_query_append = array ();
579 foreach ($this->endpoints as $endpoint) {
580 //match everything after the endpoint name, but allow for nothing to appear there
581 $epmatch = $endpoint[1] . '(/(.*))?/?$';
582 //this will be appended on to the rest of the query for each dir
583 $epquery = '&' . $endpoint[1] . '=';
584 $ep_query_append[$epmatch] = array ( $endpoint[0], $epquery );
588 //get everything up to the first rewrite tag
589 $front = substr($permalink_structure, 0, strpos($permalink_structure, '%'));
590 //build an array of the tags (note that said array ends up being in $tokens[0])
591 preg_match_all('/%.+?%/', $permalink_structure, $tokens);
593 $num_tokens = count($tokens[0]);
595 $index = $this->index; //probably 'index.php'
597 $trackbackindex = $index;
598 //build a list from the rewritecode and queryreplace arrays, that will look something like
599 //tagname=$matches[i] where i is the current $i
600 for ($i = 0; $i < $num_tokens; ++$i) {
602 $queries[$i] = $queries[$i - 1] . '&';
607 $query_token = str_replace($this->rewritecode, $this->queryreplace, $tokens[0][$i]) . $this->preg_index($i+1);
608 $queries[$i] .= $query_token;
611 //get the structure, minus any cruft (stuff that isn't tags) at the front
612 $structure = $permalink_structure;
614 $structure = str_replace($front, '', $structure);
616 //create a list of dirs to walk over, making rewrite rules for each level
617 //so for example, a $structure of /%year%/%month%/%postname% would create
618 //rewrite rules for /%year%/, /%year%/%month%/ and /%year%/%month%/%postname%
619 $structure = trim($structure, '/');
621 $dirs = explode('/', $structure);
623 $dirs[] = $structure;
625 $num_dirs = count($dirs);
627 //strip slashes from the front of $front
628 $front = preg_replace('|^/+|', '', $front);
630 //the main workhorse loop
631 $post_rewrite = array();
633 for ($j = 0; $j < $num_dirs; ++$j) {
634 //get the struct for this dir, and trim slashes off the front
635 $struct .= $dirs[$j] . '/'; //accumulate. see comment near explode('/', $structure) above
636 $struct = ltrim($struct, '/');
637 //replace tags with regexes
638 $match = str_replace($this->rewritecode, $this->rewritereplace, $struct);
639 //make a list of tags, and store how many there are in $num_toks
640 $num_toks = preg_match_all('/%.+?%/', $struct, $toks);
641 //get the 'tagname=$matches[i]'
642 $query = ( isset($queries) && is_array($queries) ) ? $queries[$num_toks - 1] : '';
644 //set up $ep_mask_specific which is used to match more specific URL types
646 case '%year%': $ep_mask_specific = EP_YEAR; break;
647 case '%monthnum%': $ep_mask_specific = EP_MONTH; break;
648 case '%day%': $ep_mask_specific = EP_DAY; break;
651 //create query for /page/xx
652 $pagematch = $match . $pageregex;
653 $pagequery = $index . '?' . $query . '&paged=' . $this->preg_index($num_toks + 1);
655 //create query for /feed/(feed|atom|rss|rss2|rdf)
656 $feedmatch = $match . $feedregex;
657 $feedquery = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
659 //create query for /(feed|atom|rss|rss2|rdf) (see comment near creation of $feedregex)
660 $feedmatch2 = $match . $feedregex2;
661 $feedquery2 = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
663 //if asked to, turn the feed queries into comment feed ones
665 $feedquery .= '&withcomments=1';
666 $feedquery2 .= '&withcomments=1';
669 //start creating the array of rewrites for this dir
671 if ($feed) //...adding on /feed/ regexes => queries
672 $rewrite = array($feedmatch => $feedquery, $feedmatch2 => $feedquery2);
673 if ($paged) //...and /page/xx ones
674 $rewrite = array_merge($rewrite, array($pagematch => $pagequery));
678 foreach ($ep_query_append as $regex => $ep) {
679 //add the endpoints on if the mask fits
680 if ($ep[0] & $ep_mask || $ep[0] & $ep_mask_specific) {
681 $rewrite[$match . $regex] = $index . '?' . $query . $ep[1] . $this->preg_index($num_toks + 2);
686 //if we've got some tags in this dir
691 //check to see if this dir is permalink-level: i.e. the structure specifies an
692 //individual post. Do this by checking it contains at least one of 1) post name,
693 //2) post ID, 3) page name, 4) timestamp (year, month, day, hour, second and
694 //minute all present). Set these flags now as we need them for the endpoints.
695 if (strpos($struct, '%postname%') !== false || strpos($struct, '%post_id%') !== false
696 || strpos($struct, '%pagename%') !== false
697 || (strpos($struct, '%year%') !== false && strpos($struct, '%monthnum%') !== false && strpos($struct, '%day%') !== false && strpos($struct, '%hour%') !== false && strpos($struct, '%minute%') !== false && strpos($struct, '%second%') !== false)) {
699 if (strpos($struct, '%pagename%') !== false)
703 //if we're creating rules for a permalink, do all the endpoints like attachments etc
706 //create query and regex for trackback
707 $trackbackmatch = $match . $trackbackregex;
708 $trackbackquery = $trackbackindex . '?' . $query . '&tb=1';
709 //trim slashes from the end of the regex for this dir
710 $match = rtrim($match, '/');
711 //get rid of brackets
712 $submatchbase = str_replace(array('(',')'),'',$match);
714 //add a rule for at attachments, which take the form of <permalink>/some-text
715 $sub1 = $submatchbase . '/([^/]+)/';
716 $sub1tb = $sub1 . $trackbackregex; //add trackback regex <permalink>/trackback/...
717 $sub1feed = $sub1 . $feedregex; //and <permalink>/feed/(atom|...)
718 $sub1feed2 = $sub1 . $feedregex2; //and <permalink>/(feed|atom...)
719 //add an ? as we don't have to match that last slash, and finally a $ so we
720 //match to the end of the URL
722 //add another rule to match attachments in the explicit form:
723 //<permalink>/attachment/some-text
724 $sub2 = $submatchbase . '/attachment/([^/]+)/';
725 $sub2tb = $sub2 . $trackbackregex; //and add trackbacks <permalink>/attachment/trackback
726 $sub2feed = $sub2 . $feedregex; //feeds, <permalink>/attachment/feed/(atom|...)
727 $sub2feed2 = $sub2 . $feedregex2; //and feeds again on to this <permalink>/attachment/(feed|atom...)
729 //create queries for these extra tag-ons we've just dealt with
730 $subquery = $index . '?attachment=' . $this->preg_index(1);
731 $subtbquery = $subquery . '&tb=1';
732 $subfeedquery = $subquery . '&feed=' . $this->preg_index(2);
734 //do endpoints for attachments
735 if (! empty($endpoint) ) { foreach ($ep_query_append as $regex => $ep) {
736 if ($ep[0] & EP_ATTACHMENT) {
737 $rewrite[$sub1 . $regex] = $subquery . '?' . $ep[1] . $this->preg_index(2);
738 $rewrite[$sub2 . $regex] = $subquery . '?' . $ep[1] . $this->preg_index(2);
742 //now we've finished with endpoints, finish off the $sub1 and $sub2 matches
746 //allow URLs like <permalink>/2 for <permalink>/page/2
747 $match = $match . '(/[0-9]+)?/?$';
748 $query = $index . '?' . $query . '&page=' . $this->preg_index($num_toks + 1);
749 } else { //not matching a permalink so this is a lot simpler
750 //close the match and finalise the query
752 $query = $index . '?' . $query;
755 //create the final array for this dir by joining the $rewrite array (which currently
756 //only contains rules/queries for trackback, pages etc) to the main regex/query for
758 $rewrite = array_merge($rewrite, array($match => $query));
760 //if we're matching a permalink, add those extras (attachments etc) on
763 $rewrite = array_merge(array($trackbackmatch => $trackbackquery), $rewrite);
765 //add regexes/queries for attachments, attachment trackbacks and so on
766 if ( ! $page ) //require <permalink>/attachment/stuff form for pages because of confusion with subpages
767 $rewrite = array_merge($rewrite, array($sub1 => $subquery, $sub1tb => $subtbquery, $sub1feed => $subfeedquery, $sub1feed2 => $subfeedquery));
768 $rewrite = array_merge(array($sub2 => $subquery, $sub2tb => $subtbquery, $sub2feed => $subfeedquery, $sub2feed2 => $subfeedquery), $rewrite);
771 //add the rules for this dir to the accumulating $post_rewrite
772 $post_rewrite = array_merge($rewrite, $post_rewrite);
774 return $post_rewrite; //the finished rules. phew!
777 function generate_rewrite_rule($permalink_structure, $walk_dirs = false) {
778 return $this->generate_rewrite_rules($permalink_structure, EP_NONE, false, false, false, $walk_dirs);
782 * Construct rewrite matches and queries from permalink structure.
783 * Returns an associate array of matches and queries.
785 function rewrite_rules() {
788 if (empty($this->permalink_structure)) {
793 $robots_rewrite = array('robots.txt$' => $this->index . '?robots=1');
795 //Default Feed rules - These are require to allow for the direct access files to work with permalink structure starting with %category%
796 $default_feeds = array( '.*/wp-atom.php$' => $this->index .'?feed=atom',
797 '.*/wp-rdf.php$' => $this->index .'?feed=rdf',
798 '.*/wp-rss.php$' => $this->index .'?feed=rss',
799 '.*/wp-rss2.php$' => $this->index .'?feed=rss2',
800 '.*/wp-feed.php$' => $this->index .'?feed=feed',
801 '.*/wp-commentsrss2.php$' => $this->index . '?feed=rss2&withcomments=1');
804 $post_rewrite = $this->generate_rewrite_rules($this->permalink_structure, EP_PERMALINK);
805 $post_rewrite = apply_filters('post_rewrite_rules', $post_rewrite);
808 $date_rewrite = $this->generate_rewrite_rules($this->get_date_permastruct(), EP_DATE);
809 $date_rewrite = apply_filters('date_rewrite_rules', $date_rewrite);
812 $root_rewrite = $this->generate_rewrite_rules($this->root . '/', EP_ROOT);
813 $root_rewrite = apply_filters('root_rewrite_rules', $root_rewrite);
816 $comments_rewrite = $this->generate_rewrite_rules($this->root . $this->comments_base, EP_COMMENTS, true, true, true, false);
817 $comments_rewrite = apply_filters('comments_rewrite_rules', $comments_rewrite);
820 $search_structure = $this->get_search_permastruct();
821 $search_rewrite = $this->generate_rewrite_rules($search_structure, EP_SEARCH);
822 $search_rewrite = apply_filters('search_rewrite_rules', $search_rewrite);
825 $category_rewrite = $this->generate_rewrite_rules($this->get_category_permastruct(), EP_CATEGORIES);
826 $category_rewrite = apply_filters('category_rewrite_rules', $category_rewrite);
829 $tag_rewrite = $this->generate_rewrite_rules($this->get_tag_permastruct(), EP_TAGS);
830 $tag_rewrite = apply_filters('tag_rewrite_rules', $tag_rewrite);
833 $author_rewrite = $this->generate_rewrite_rules($this->get_author_permastruct(), EP_AUTHORS);
834 $author_rewrite = apply_filters('author_rewrite_rules', $author_rewrite);
837 $page_rewrite = $this->page_rewrite_rules();
838 $page_rewrite = apply_filters('page_rewrite_rules', $page_rewrite);
840 // Extra permastructs
841 foreach ( $this->extra_permastructs as $permastruct )
842 $this->extra_rules_top = array_merge($this->extra_rules_top, $this->generate_rewrite_rules($permastruct, EP_NONE));
844 // Put them together.
845 if ( $this->use_verbose_page_rules )
846 $this->rules = array_merge($this->extra_rules_top, $robots_rewrite, $default_feeds, $page_rewrite, $root_rewrite, $comments_rewrite, $search_rewrite, $category_rewrite, $tag_rewrite, $author_rewrite, $date_rewrite, $post_rewrite, $this->extra_rules);
848 $this->rules = array_merge($this->extra_rules_top, $robots_rewrite, $default_feeds, $root_rewrite, $comments_rewrite, $search_rewrite, $category_rewrite, $tag_rewrite, $author_rewrite, $date_rewrite, $post_rewrite, $page_rewrite, $this->extra_rules);
850 do_action_ref_array('generate_rewrite_rules', array(&$this));
851 $this->rules = apply_filters('rewrite_rules_array', $this->rules);
856 function wp_rewrite_rules() {
857 $this->rules = get_option('rewrite_rules');
858 if ( empty($this->rules) ) {
859 $this->matches = 'matches';
860 $this->rewrite_rules();
861 update_option('rewrite_rules', $this->rules);
867 function mod_rewrite_rules() {
868 if ( ! $this->using_permalinks()) {
872 $site_root = parse_url(get_option('siteurl'));
873 $site_root = trailingslashit($site_root['path']);
875 $home_root = parse_url(get_option('home'));
876 $home_root = trailingslashit($home_root['path']);
878 $rules = "<IfModule mod_rewrite.c>\n";
879 $rules .= "RewriteEngine On\n";
880 $rules .= "RewriteBase $home_root\n";
882 //add in the rules that don't redirect to WP's index.php (and thus shouldn't be handled by WP at all)
883 foreach ($this->non_wp_rules as $match => $query) {
884 // Apache 1.3 does not support the reluctant (non-greedy) modifier.
885 $match = str_replace('.+?', '.+', $match);
887 // If the match is unanchored and greedy, prepend rewrite conditions
888 // to avoid infinite redirects and eclipsing of real files.
889 if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) {
893 $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
896 if ($this->use_verbose_rules) {
898 $rewrite = $this->rewrite_rules();
899 $num_rules = count($rewrite);
900 $rules .= "RewriteCond %{REQUEST_FILENAME} -f [OR]\n" .
901 "RewriteCond %{REQUEST_FILENAME} -d\n" .
902 "RewriteRule ^.*$ - [S=$num_rules]\n";
904 foreach ($rewrite as $match => $query) {
905 // Apache 1.3 does not support the reluctant (non-greedy) modifier.
906 $match = str_replace('.+?', '.+', $match);
908 // If the match is unanchored and greedy, prepend rewrite conditions
909 // to avoid infinite redirects and eclipsing of real files.
910 if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) {
914 if (strpos($query, $this->index) !== false) {
915 $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
917 $rules .= 'RewriteRule ^' . $match . ' ' . $site_root . $query . " [QSA,L]\n";
921 $rules .= "RewriteCond %{REQUEST_FILENAME} !-f\n" .
922 "RewriteCond %{REQUEST_FILENAME} !-d\n" .
923 "RewriteRule . {$home_root}{$this->index} [L]\n";
926 $rules .= "</IfModule>\n";
928 $rules = apply_filters('mod_rewrite_rules', $rules);
929 $rules = apply_filters('rewrite_rules', $rules); // Deprecated
934 //Add a straight rewrite rule
935 function add_rule($regex, $redirect, $after = 'bottom') {
936 //get everything up to the first ?
937 $index = (strpos($redirect, '?') == false ? strlen($redirect) : strpos($redirect, '?'));
938 $front = substr($redirect, 0, $index);
939 if ($front != $this->index) { //it doesn't redirect to WP's index.php
940 $this->add_external_rule($regex, $redirect);
942 if ( 'bottom' == $after)
943 $this->extra_rules = array_merge($this->extra_rules, array($regex => $redirect));
945 $this->extra_rules_top = array_merge($this->extra_rules_top, array($regex => $redirect));
946 //$this->extra_rules[$regex] = $redirect;
950 //add a rule that doesn't redirect to index.php
951 function add_external_rule($regex, $redirect) {
952 $this->non_wp_rules[$regex] = $redirect;
955 //add an endpoint, like /trackback/, to be inserted after certain URL types (specified in $places)
956 function add_endpoint($name, $places) {
958 $this->endpoints[] = array ( $places, $name );
959 $wp->add_query_var($name);
962 function add_permastruct($name, $struct, $with_front = true) {
964 $struct = $this->front . $struct;
965 $this->extra_permastructs[$name] = $struct;
968 function flush_rules() {
969 delete_option('rewrite_rules');
970 $this->wp_rewrite_rules();
971 if ( function_exists('save_mod_rewrite_rules') )
972 save_mod_rewrite_rules();
976 $this->extra_rules = $this->non_wp_rules = $this->endpoints = array();
977 $this->permalink_structure = get_option('permalink_structure');
978 $this->front = substr($this->permalink_structure, 0, strpos($this->permalink_structure, '%'));
980 if ($this->using_index_permalinks()) {
981 $this->root = $this->index . '/';
983 $this->category_base = get_option( 'category_base' );
984 $this->tag_base = get_option( 'tag_base' );
985 unset($this->category_structure);
986 unset($this->author_structure);
987 unset($this->date_structure);
988 unset($this->page_structure);
989 unset($this->search_structure);
990 unset($this->feed_structure);
991 unset($this->comment_feed_structure);
992 $this->use_trailing_slashes = ( substr($this->permalink_structure, -1, 1) == '/' ) ? true : false;
994 // Enable generic rules for pages if permalink structure doesn't begin with a wildcard.
995 $structure = ltrim($this->permalink_structure, '/');
996 if ( $this->using_index_permalinks() )
997 $structure = ltrim($this->permalink_structure, $this->index . '/');
998 if ( 0 === strpos($structure, '%postname%') ||
999 0 === strpos($structure, '%category%') ||
1000 0 === strpos($structure, '%tag%') ||
1001 0 === strpos($structure, '%author%') )
1002 $this->use_verbose_page_rules = true;
1004 $this->use_verbose_page_rules = false;
1007 function set_permalink_structure($permalink_structure) {
1008 if ($permalink_structure != $this->permalink_structure) {
1009 update_option('permalink_structure', $permalink_structure);
1014 function set_category_base($category_base) {
1015 if ($category_base != $this->category_base) {
1016 update_option('category_base', $category_base);
1021 function set_tag_base( $tag_base ) {
1022 if ( $tag_base != $this->tag_base ) {
1023 update_option( 'tag_base', $tag_base );
1028 function WP_Rewrite() {