3 * WordPress Rewrite API
10 * Add a straight rewrite rule.
12 * @see WP_Rewrite::add_rule() for long description.
15 * @param string $regex Regular Expression to match request against.
16 * @param string $redirect Page to redirect to.
17 * @param string $after Optional, default is 'bottom'. Where to add rule, can also be 'top'.
19 function add_rewrite_rule($regex, $redirect, $after = 'bottom') {
21 $wp_rewrite->add_rule($regex, $redirect, $after);
25 * Add a new rewrite tag (like %postname%).
27 * The $query parameter is optional. If it is omitted you must ensure that
28 * you call this on, or before, the 'init' hook. This is because $query defaults
29 * to "$tag=", and for this to work a new query var has to be added.
31 * @see WP_Rewrite::add_rewrite_tag()
34 * @param string $tag Name of the new rewrite tag.
35 * @param string $regex Regular expression to substitute the tag for in rewrite rules.
36 * @param string $query String to append to the rewritten query. Must end in '='. Optional.
38 function add_rewrite_tag( $tag, $regex, $query = '' ) {
39 // validate the tag's name
40 if ( strlen( $tag ) < 3 || $tag[0] != '%' || $tag[ strlen($tag) - 1 ] != '%' )
43 global $wp_rewrite, $wp;
45 if ( empty( $query ) ) {
46 $qv = trim( $tag, '%' );
47 $wp->add_query_var( $qv );
51 $wp_rewrite->add_rewrite_tag( $tag, $regex, $query );
55 * Add permalink structure.
57 * @see WP_Rewrite::add_permastruct()
60 * @param string $name Name for permalink structure.
61 * @param string $struct Permalink structure.
62 * @param array $args Optional configuration for building the rules from the permalink structure,
63 * see {@link WP_Rewrite::add_permastruct()} for full details.
65 function add_permastruct( $name, $struct, $args = array() ) {
68 // backwards compatibility for the old parameters: $with_front and $ep_mask
69 if ( ! is_array( $args ) )
70 $args = array( 'with_front' => $args );
71 if ( func_num_args() == 4 )
72 $args['ep_mask'] = func_get_arg( 3 );
74 return $wp_rewrite->add_permastruct( $name, $struct, $args );
78 * Add a new feed type like /atom1/.
82 * @param string $feedname
83 * @param callback $function Callback to run on feed display.
84 * @return string Feed action name.
86 function add_feed($feedname, $function) {
88 if ( ! in_array($feedname, $wp_rewrite->feeds) ) //override the file if it is
89 $wp_rewrite->feeds[] = $feedname;
90 $hook = 'do_feed_' . $feedname;
91 // Remove default function hook
92 remove_action($hook, $hook);
93 add_action($hook, $function, 10, 1);
98 * Remove rewrite rules and then recreate rewrite rules.
100 * @see WP_Rewrite::flush_rules()
103 * @param bool $hard Whether to update .htaccess (hard flush) or just update
104 * rewrite_rules transient (soft flush). Default is true (hard).
106 function flush_rewrite_rules( $hard = true ) {
108 $wp_rewrite->flush_rules( $hard );
112 * Endpoint Mask for default, which is nothing.
116 define('EP_NONE', 0);
119 * Endpoint Mask for Permalink.
123 define('EP_PERMALINK', 1);
126 * Endpoint Mask for Attachment.
130 define('EP_ATTACHMENT', 2);
133 * Endpoint Mask for date.
137 define('EP_DATE', 4);
140 * Endpoint Mask for year
144 define('EP_YEAR', 8);
147 * Endpoint Mask for month.
151 define('EP_MONTH', 16);
154 * Endpoint Mask for day.
158 define('EP_DAY', 32);
161 * Endpoint Mask for root.
165 define('EP_ROOT', 64);
168 * Endpoint Mask for comments.
172 define('EP_COMMENTS', 128);
175 * Endpoint Mask for searches.
179 define('EP_SEARCH', 256);
182 * Endpoint Mask for categories.
186 define('EP_CATEGORIES', 512);
189 * Endpoint Mask for tags.
193 define('EP_TAGS', 1024);
196 * Endpoint Mask for authors.
200 define('EP_AUTHORS', 2048);
203 * Endpoint Mask for pages.
207 define('EP_PAGES', 4096);
210 * Endpoint Mask for all archive views.
214 define( 'EP_ALL_ARCHIVES', EP_DATE | EP_YEAR | EP_MONTH | EP_DAY | EP_CATEGORIES | EP_TAGS | EP_AUTHORS );
217 * Endpoint Mask for everything.
221 define( 'EP_ALL', EP_PERMALINK | EP_ATTACHMENT | EP_ROOT | EP_COMMENTS | EP_SEARCH | EP_PAGES | EP_ALL_ARCHIVES );
224 * Add an endpoint, like /trackback/.
226 * Adding an endpoint creates extra rewrite rules for each of the matching
227 * places specified by the provided bitmask. For example:
229 * add_rewrite_endpoint( 'json', EP_PERMALINK | EP_PAGES );
231 * will add a new rewrite rule ending with "json(/(.*))?/?$" for every permastruct
232 * that describes a permalink (post) or page. This is rewritten to "json=$match"
233 * where $match is the part of the URL matched by the endpoint regex (e.g. "foo" in
234 * "[permalink]/json/foo/").
236 * A new query var with the same name as the endpoint will also be created.
238 * When specifying $places ensure that you are using the EP_* constants (or a
239 * combination of them using the bitwise OR operator) as their values are not
240 * guaranteed to remain static (especially `EP_ALL`).
242 * Be sure to flush the rewrite rules - {@see flush_rewrite_rules()} - when your plugin gets
243 * activated and deactivated.
246 * @see WP_Rewrite::add_endpoint()
247 * @global object $wp_rewrite
249 * @param string $name Name of the endpoint.
250 * @param int $places Endpoint mask describing the places the endpoint should be added.
251 * @param string $query_var Name of the corresponding query variable. Defaults to $name.
253 function add_rewrite_endpoint( $name, $places, $query_var = null ) {
255 $wp_rewrite->add_endpoint( $name, $places, $query_var );
259 * Filter the URL base for taxonomies.
261 * To remove any manually prepended /index.php/.
266 * @param string $base The taxonomy base that we're going to filter
269 function _wp_filter_taxonomy_base( $base ) {
270 if ( !empty( $base ) ) {
271 $base = preg_replace( '|^/index\.php/|', '', $base );
272 $base = trim( $base, '/' );
278 * Examine a url and try to determine the post ID it represents.
280 * Checks are supposedly from the hosted site blog.
284 * @param string $url Permalink to check.
285 * @return int Post ID, or 0 on failure.
287 function url_to_postid($url) {
291 * Filter the URL to derive the post ID from.
295 * @param string $url The URL to derive the post ID from.
297 $url = apply_filters( 'url_to_postid', $url );
299 // First, check to see if there is a 'p=N' or 'page_id=N' to match against
300 if ( preg_match('#[?&](p|page_id|attachment_id)=(\d+)#', $url, $values) ) {
301 $id = absint($values[2]);
306 // Check to see if we are using rewrite rules
307 $rewrite = $wp_rewrite->wp_rewrite_rules();
309 // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
310 if ( empty($rewrite) )
313 // Get rid of the #anchor
314 $url_split = explode('#', $url);
315 $url = $url_split[0];
317 // Get rid of URL ?query=string
318 $url_split = explode('?', $url);
319 $url = $url_split[0];
321 // Add 'www.' if it is absent and should be there
322 if ( false !== strpos(home_url(), '://www.') && false === strpos($url, '://www.') )
323 $url = str_replace('://', '://www.', $url);
325 // Strip 'www.' if it is present and shouldn't be
326 if ( false === strpos(home_url(), '://www.') )
327 $url = str_replace('://www.', '://', $url);
329 // Strip 'index.php/' if we're not using path info permalinks
330 if ( !$wp_rewrite->using_index_permalinks() )
331 $url = str_replace( $wp_rewrite->index . '/', '', $url );
333 if ( false !== strpos( trailingslashit( $url ), home_url( '/' ) ) ) {
334 // Chop off http://domain.com/[path]
335 $url = str_replace(home_url(), '', $url);
337 // Chop off /path/to/blog
338 $home_path = parse_url( home_url( '/' ) );
339 $home_path = isset( $home_path['path'] ) ? $home_path['path'] : '' ;
340 $url = preg_replace( sprintf( '#^%s#', preg_quote( $home_path ) ), '', trailingslashit( $url ) );
343 // Trim leading and lagging slashes
344 $url = trim($url, '/');
347 $post_type_query_vars = array();
349 foreach ( get_post_types( array() , 'objects' ) as $post_type => $t ) {
350 if ( ! empty( $t->query_var ) )
351 $post_type_query_vars[ $t->query_var ] = $post_type;
355 $request_match = $request;
356 foreach ( (array)$rewrite as $match => $query) {
358 // If the requesting file is the anchor of the match, prepend it
360 if ( !empty($url) && ($url != $request) && (strpos($match, $url) === 0) )
361 $request_match = $url . '/' . $request;
363 if ( preg_match("#^$match#", $request_match, $matches) ) {
365 if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
366 // This is a verbose page match, let's check to be sure about it.
367 if ( ! get_page_by_path( $matches[ $varmatch[1] ] ) )
372 // Trim the query of everything up to the '?'.
373 $query = preg_replace("!^.+\?!", '', $query);
375 // Substitute the substring matches into the query.
376 $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
378 // Filter out non-public query vars
380 parse_str( $query, $query_vars );
382 foreach ( (array) $query_vars as $key => $value ) {
383 if ( in_array( $key, $wp->public_query_vars ) ){
384 $query[$key] = $value;
385 if ( isset( $post_type_query_vars[$key] ) ) {
386 $query['post_type'] = $post_type_query_vars[$key];
387 $query['name'] = $value;
393 $query = new WP_Query( $query );
394 if ( ! empty( $query->posts ) && $query->is_singular )
395 return $query->post->ID;
404 * WordPress Rewrite Component.
406 * The WordPress Rewrite class writes the rewrite module rules to the .htaccess
407 * file. It also handles parsing the request to get the correct setup for the
408 * WordPress Query class.
410 * The Rewrite along with WP class function as a front controller for WordPress.
411 * You can add rules to trigger your page view and processing using this
412 * component. The full functionality of a front controller does not exist,
413 * meaning you can't define how the template files load based on the rewrite
420 * Permalink structure for posts.
426 var $permalink_structure;
429 * Whether to add trailing slashes.
435 var $use_trailing_slashes;
438 * Base for the author permalink structure (example.com/$author_base/authorname).
444 var $author_base = 'author';
447 * Permalink structure for author archives.
453 var $author_structure;
456 * Permalink structure for date archives.
465 * Permalink structure for pages.
474 * Base of the search permalink structure (example.com/$search_base/query).
480 var $search_base = 'search';
483 * Permalink structure for searches.
489 var $search_structure;
492 * Comments permalink base.
498 var $comments_base = 'comments';
501 * Pagination permalink base.
507 var $pagination_base = 'page';
510 * Feed permalink base.
516 var $feed_base = 'feed';
519 * Comments feed permalink structure.
525 var $comments_feed_structure;
528 * Feed request permalink structure.
537 * The static portion of the post permalink structure.
539 * If the permalink structure is "/archive/%post_id%" then the front
540 * is "/archive/". If the permalink structure is "/%year%/%postname%/"
541 * then the front is "/".
543 * @see WP_Rewrite::init()
551 * The prefix for all permalink structures.
553 * If PATHINFO/index permalinks are in use then the root is the value of
554 * {@link WP_Rewrite::$index} with a trailing slash appended. Otherwise
555 * the root will be empty.
557 * @see WP_Rewrite::init()
558 * @see WP_Rewrite::using_index_permalinks()
566 * The name of the index file which is the entry point to all requests.
572 public $index = 'index.php';
575 * Variable name to use for regex matches in the rewritten query.
584 * Rewrite rules to match against the request to find the redirect or query.
593 * Additional rules added external to the rewrite class.
595 * Those not generated by the class, see add_rewrite_rule().
601 var $extra_rules = array();
604 * Additional rules that belong at the beginning to match first.
606 * Those not generated by the class, see add_rewrite_rule().
612 var $extra_rules_top = array();
615 * Rules that don't redirect to WordPress' index.php.
617 * These rules are written to the mod_rewrite portion of the .htaccess,
618 * and are added by {@link add_external_rule()}.
624 var $non_wp_rules = array();
627 * Extra permalink structures, e.g. categories, added by {@link add_permastruct()}.
633 var $extra_permastructs = array();
636 * Endpoints (like /trackback/) added by {@link add_rewrite_endpoint()}.
645 * Whether to write every mod_rewrite rule for WordPress into the .htaccess file.
647 * This is off by default, turning it on might print a lot of rewrite rules
648 * to the .htaccess file.
650 * @see WP_Rewrite::mod_rewrite_rules()
655 public $use_verbose_rules = false;
658 * Could post permalinks be confused with those of pages?
660 * If the first rewrite tag in the post permalink structure is one that could
661 * also match a page name (e.g. %postname% or %author%) then this flag is
662 * set to true. Prior to WordPress 3.3 this flag indicated that every page
663 * would have a set of rules added to the top of the rewrite rules array.
664 * Now it tells {@link WP::parse_request()} to check if a URL matching the
665 * page permastruct is actually a page before accepting it.
667 * @link https://core.trac.wordpress.org/ticket/16687
668 * @see WP_Rewrite::init()
673 public $use_verbose_page_rules = true;
676 * Rewrite tags that can be used in permalink structures.
678 * These are translated into the regular expressions stored in
679 * {@link WP_Rewrite::$rewritereplace} and are rewritten to the
680 * query variables listed in {@link WP_Rewrite::$queryreplace}.
682 * Additional tags can be added with {@link add_rewrite_tag()}.
688 var $rewritecode = array(
703 * Regular expressions to be substituted into rewrite rules in place
704 * of rewrite tags, see {@link WP_Rewrite::$rewritecode}.
710 var $rewritereplace = array(
725 * Query variables that rewrite tags map to, see {@link WP_Rewrite::$rewritecode}.
731 var $queryreplace = array(
746 * Supported default feeds.
752 var $feeds = array( 'feed', 'rdf', 'rss', 'rss2', 'atom' );
755 * Whether permalinks are being used.
757 * This can be either rewrite module or permalink in the HTTP query string.
762 * @return bool True, if permalinks are enabled.
764 public function using_permalinks() {
765 return ! empty($this->permalink_structure);
769 * Whether permalinks are being used and rewrite module is not enabled.
771 * Means that permalink links are enabled and index.php is in the URL.
778 public function using_index_permalinks() {
779 if ( empty($this->permalink_structure) )
782 // If the index is not in the permalink, we're using mod_rewrite.
783 if ( preg_match('#^/*' . $this->index . '#', $this->permalink_structure) )
790 * Whether permalinks are being used and rewrite module is enabled.
792 * Using permalinks and index.php is not in the URL.
799 public function using_mod_rewrite_permalinks() {
800 if ( $this->using_permalinks() && ! $this->using_index_permalinks() )
807 * Index for matches for usage in preg_*() functions.
809 * The format of the string is, with empty matches property value, '$NUM'.
810 * The 'NUM' will be replaced with the value in the $number parameter. With
811 * the matches property not empty, the value of the returned string will
812 * contain that value of the matches property. The format then will be
813 * '$MATCHES[NUM]', with MATCHES as the value in the property and NUM the
814 * value of the $number parameter.
819 * @param int $number Index number.
822 public function preg_index($number) {
826 if ( ! empty($this->matches) ) {
827 $match_prefix = '$' . $this->matches . '[';
831 return "$match_prefix$number$match_suffix";
835 * Retrieve all page and attachments for pages URIs.
837 * The attachments are for those that have pages as parents and will be
843 * @return array Array of page URIs as first element and attachment URIs as second element.
845 public function page_uri_index() {
848 //get pages in order of hierarchy, i.e. children after parents
849 $pages = $wpdb->get_results("SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'page' AND post_status != 'auto-draft'");
850 $posts = get_page_hierarchy( $pages );
852 // If we have no pages get out quick
854 return array( array(), array() );
856 //now reverse it, because we need parents after children for rewrite rules to work properly
857 $posts = array_reverse($posts, true);
859 $page_uris = array();
860 $page_attachment_uris = array();
862 foreach ( $posts as $id => $post ) {
864 $uri = get_page_uri($id);
865 $attachments = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'attachment' AND post_parent = %d", $id ));
866 if ( !empty($attachments) ) {
867 foreach ( $attachments as $attachment ) {
868 $attach_uri = get_page_uri($attachment->ID);
869 $page_attachment_uris[$attach_uri] = $attachment->ID;
873 $page_uris[$uri] = $id;
876 return array( $page_uris, $page_attachment_uris );
880 * Retrieve all of the rewrite rules for pages.
887 public function page_rewrite_rules() {
888 // the extra .? at the beginning prevents clashes with other regular expressions in the rules array
889 $this->add_rewrite_tag( '%pagename%', '(.?.+?)', 'pagename=' );
891 return $this->generate_rewrite_rules( $this->get_page_permastruct(), EP_PAGES, true, true, false, false );
895 * Retrieve date permalink structure, with year, month, and day.
897 * The permalink structure for the date, if not set already depends on the
898 * permalink structure. It can be one of three formats. The first is year,
899 * month, day; the second is day, month, year; and the last format is month,
900 * day, year. These are matched against the permalink structure for which
901 * one is used. If none matches, then the default will be used, which is
904 * Prevents post ID and date permalinks from overlapping. In the case of
905 * post_id, the date permalink will be prepended with front permalink with
906 * 'date/' before the actual permalink to form the complete date permalink
912 * @return string|false False on no permalink structure. Date permalink structure.
914 public function get_date_permastruct() {
915 if ( isset($this->date_structure) )
916 return $this->date_structure;
918 if ( empty($this->permalink_structure) ) {
919 $this->date_structure = '';
923 // The date permalink must have year, month, and day separated by slashes.
924 $endians = array('%year%/%monthnum%/%day%', '%day%/%monthnum%/%year%', '%monthnum%/%day%/%year%');
926 $this->date_structure = '';
929 foreach ( $endians as $endian ) {
930 if ( false !== strpos($this->permalink_structure, $endian) ) {
931 $date_endian= $endian;
936 if ( empty($date_endian) )
937 $date_endian = '%year%/%monthnum%/%day%';
939 // Do not allow the date tags and %post_id% to overlap in the permalink
940 // structure. If they do, move the date tags to $front/date/.
941 $front = $this->front;
942 preg_match_all('/%.+?%/', $this->permalink_structure, $tokens);
944 foreach ( (array) $tokens[0] as $token) {
945 if ( '%post_id%' == $token && ($tok_index <= 3) ) {
946 $front = $front . 'date/';
952 $this->date_structure = $front . $date_endian;
954 return $this->date_structure;
958 * Retrieve the year permalink structure without month and day.
960 * Gets the date permalink structure and strips out the month and day
961 * permalink structures.
966 * @return false|string False on failure. Year structure on success.
968 public function get_year_permastruct() {
969 $structure = $this->get_date_permastruct();
971 if ( empty($structure) )
974 $structure = str_replace('%monthnum%', '', $structure);
975 $structure = str_replace('%day%', '', $structure);
977 $structure = preg_replace('#/+#', '/', $structure);
983 * Retrieve the month permalink structure without day and with year.
985 * Gets the date permalink structure and strips out the day permalink
986 * structures. Keeps the year permalink structure.
991 * @return false|string False on failure. Year/Month structure on success.
993 public function get_month_permastruct() {
994 $structure = $this->get_date_permastruct();
996 if ( empty($structure) )
999 $structure = str_replace('%day%', '', $structure);
1001 $structure = preg_replace('#/+#', '/', $structure);
1007 * Retrieve the day permalink structure with month and year.
1009 * Keeps date permalink structure with all year, month, and day.
1014 * @return string|false False on failure. Year/Month/Day structure on success.
1016 public function get_day_permastruct() {
1017 return $this->get_date_permastruct();
1021 * Retrieve the permalink structure for categories.
1023 * If the category_base property has no value, then the category structure
1024 * will have the front property value, followed by 'category', and finally
1025 * '%category%'. If it does, then the root property will be used, along with
1026 * the category_base property value.
1031 * @return bool|string False on failure. Category permalink structure.
1033 public function get_category_permastruct() {
1034 return $this->get_extra_permastruct('category');
1038 * Retrieve the permalink structure for tags.
1040 * If the tag_base property has no value, then the tag structure will have
1041 * the front property value, followed by 'tag', and finally '%tag%'. If it
1042 * does, then the root property will be used, along with the tag_base
1048 * @return bool|string False on failure. Tag permalink structure.
1050 public function get_tag_permastruct() {
1051 return $this->get_extra_permastruct('post_tag');
1055 * Retrieve extra permalink structure by name.
1060 * @param string $name Permalink structure name.
1061 * @return string|bool False if not found. Permalink structure string.
1063 public function get_extra_permastruct($name) {
1064 if ( empty($this->permalink_structure) )
1067 if ( isset($this->extra_permastructs[$name]) )
1068 return $this->extra_permastructs[$name]['struct'];
1074 * Retrieve the author permalink structure.
1076 * The permalink structure is front property, author base, and finally
1077 * '/%author%'. Will set the author_structure property and then return it
1078 * without attempting to set the value again.
1083 * @return string|false False if not found. Permalink structure string.
1085 public function get_author_permastruct() {
1086 if ( isset($this->author_structure) )
1087 return $this->author_structure;
1089 if ( empty($this->permalink_structure) ) {
1090 $this->author_structure = '';
1094 $this->author_structure = $this->front . $this->author_base . '/%author%';
1096 return $this->author_structure;
1100 * Retrieve the search permalink structure.
1102 * The permalink structure is root property, search base, and finally
1103 * '/%search%'. Will set the search_structure property and then return it
1104 * without attempting to set the value again.
1109 * @return string|false False if not found. Permalink structure string.
1111 public function get_search_permastruct() {
1112 if ( isset($this->search_structure) )
1113 return $this->search_structure;
1115 if ( empty($this->permalink_structure) ) {
1116 $this->search_structure = '';
1120 $this->search_structure = $this->root . $this->search_base . '/%search%';
1122 return $this->search_structure;
1126 * Retrieve the page permalink structure.
1128 * The permalink structure is root property, and '%pagename%'. Will set the
1129 * page_structure property and then return it without attempting to set the
1135 * @return string|false False if not found. Permalink structure string.
1137 public function get_page_permastruct() {
1138 if ( isset($this->page_structure) )
1139 return $this->page_structure;
1141 if (empty($this->permalink_structure)) {
1142 $this->page_structure = '';
1146 $this->page_structure = $this->root . '%pagename%';
1148 return $this->page_structure;
1152 * Retrieve the feed permalink structure.
1154 * The permalink structure is root property, feed base, and finally
1155 * '/%feed%'. Will set the feed_structure property and then return it
1156 * without attempting to set the value again.
1161 * @return string|false False if not found. Permalink structure string.
1163 public function get_feed_permastruct() {
1164 if ( isset($this->feed_structure) )
1165 return $this->feed_structure;
1167 if ( empty($this->permalink_structure) ) {
1168 $this->feed_structure = '';
1172 $this->feed_structure = $this->root . $this->feed_base . '/%feed%';
1174 return $this->feed_structure;
1178 * Retrieve the comment feed permalink structure.
1180 * The permalink structure is root property, comment base property, feed
1181 * base and finally '/%feed%'. Will set the comment_feed_structure property
1182 * and then return it without attempting to set the value again.
1187 * @return string|bool False if not found. Permalink structure string.
1189 public function get_comment_feed_permastruct() {
1190 if ( isset($this->comment_feed_structure) )
1191 return $this->comment_feed_structure;
1193 if (empty($this->permalink_structure)) {
1194 $this->comment_feed_structure = '';
1198 $this->comment_feed_structure = $this->root . $this->comments_base . '/' . $this->feed_base . '/%feed%';
1200 return $this->comment_feed_structure;
1204 * Add or update existing rewrite tags (e.g. %postname%).
1206 * If the tag already exists, replace the existing pattern and query for
1207 * that tag, otherwise add the new tag.
1209 * @see WP_Rewrite::$rewritecode
1210 * @see WP_Rewrite::$rewritereplace
1211 * @see WP_Rewrite::$queryreplace
1215 * @param string $tag Name of the rewrite tag to add or update.
1216 * @param string $regex Regular expression to substitute the tag for in rewrite rules.
1217 * @param string $query String to append to the rewritten query. Must end in '='.
1219 public function add_rewrite_tag( $tag, $regex, $query ) {
1220 $position = array_search( $tag, $this->rewritecode );
1221 if ( false !== $position && null !== $position ) {
1222 $this->rewritereplace[ $position ] = $regex;
1223 $this->queryreplace[ $position ] = $query;
1225 $this->rewritecode[] = $tag;
1226 $this->rewritereplace[] = $regex;
1227 $this->queryreplace[] = $query;
1232 * Generate rewrite rules from a permalink structure.
1234 * The main WP_Rewrite function for building the rewrite rule list. The
1235 * contents of the function is a mix of black magic and regular expressions,
1236 * so best just ignore the contents and move to the parameters.
1241 * @param string $permalink_structure The permalink structure.
1242 * @param int $ep_mask Endpoint mask defining what endpoints are added to the structure. Default is EP_NONE.
1243 * @param bool $paged Should archive pagination rules be added for the structure? Default is true.
1244 * @param bool $feed Should feed rewrite rules be added for the structure? Default is true.
1245 * @param bool $forcomments Should the feed rules be a query for a comments feed? Default is false.
1246 * @param bool $walk_dirs Should the 'directories' making up the structure be walked over and rewrite rules
1247 * built for each in turn? Default is true.
1248 * @param bool $endpoints Should endpoints be applied to the generated rewrite rules? Default is true.
1249 * @return array Rewrite rule list.
1251 public function generate_rewrite_rules($permalink_structure, $ep_mask = EP_NONE, $paged = true, $feed = true, $forcomments = false, $walk_dirs = true, $endpoints = true) {
1252 //build a regex to match the feed section of URLs, something like (feed|atom|rss|rss2)/?
1254 foreach ( (array) $this->feeds as $feed_name)
1255 $feedregex2 .= $feed_name . '|';
1256 $feedregex2 = '(' . trim($feedregex2, '|') . ')/?$';
1258 //$feedregex is identical but with /feed/ added on as well, so URLs like <permalink>/feed/atom
1259 //and <permalink>/atom are both possible
1260 $feedregex = $this->feed_base . '/' . $feedregex2;
1262 //build a regex to match the trackback and page/xx parts of URLs
1263 $trackbackregex = 'trackback/?$';
1264 $pageregex = $this->pagination_base . '/?([0-9]{1,})/?$';
1265 $commentregex = 'comment-page-([0-9]{1,})/?$';
1267 //build up an array of endpoint regexes to append => queries to append
1269 $ep_query_append = array ();
1270 foreach ( (array) $this->endpoints as $endpoint) {
1271 //match everything after the endpoint name, but allow for nothing to appear there
1272 $epmatch = $endpoint[1] . '(/(.*))?/?$';
1273 //this will be appended on to the rest of the query for each dir
1274 $epquery = '&' . $endpoint[2] . '=';
1275 $ep_query_append[$epmatch] = array ( $endpoint[0], $epquery );
1279 //get everything up to the first rewrite tag
1280 $front = substr($permalink_structure, 0, strpos($permalink_structure, '%'));
1281 //build an array of the tags (note that said array ends up being in $tokens[0])
1282 preg_match_all('/%.+?%/', $permalink_structure, $tokens);
1284 $num_tokens = count($tokens[0]);
1286 $index = $this->index; //probably 'index.php'
1287 $feedindex = $index;
1288 $trackbackindex = $index;
1289 //build a list from the rewritecode and queryreplace arrays, that will look something like
1290 //tagname=$matches[i] where i is the current $i
1291 for ( $i = 0; $i < $num_tokens; ++$i ) {
1293 $queries[$i] = $queries[$i - 1] . '&';
1297 $query_token = str_replace($this->rewritecode, $this->queryreplace, $tokens[0][$i]) . $this->preg_index($i+1);
1298 $queries[$i] .= $query_token;
1301 //get the structure, minus any cruft (stuff that isn't tags) at the front
1302 $structure = $permalink_structure;
1303 if ( $front != '/' )
1304 $structure = str_replace($front, '', $structure);
1306 //create a list of dirs to walk over, making rewrite rules for each level
1307 //so for example, a $structure of /%year%/%monthnum%/%postname% would create
1308 //rewrite rules for /%year%/, /%year%/%monthnum%/ and /%year%/%monthnum%/%postname%
1309 $structure = trim($structure, '/');
1310 $dirs = $walk_dirs ? explode('/', $structure) : array( $structure );
1311 $num_dirs = count($dirs);
1313 //strip slashes from the front of $front
1314 $front = preg_replace('|^/+|', '', $front);
1316 //the main workhorse loop
1317 $post_rewrite = array();
1319 for ( $j = 0; $j < $num_dirs; ++$j ) {
1320 //get the struct for this dir, and trim slashes off the front
1321 $struct .= $dirs[$j] . '/'; //accumulate. see comment near explode('/', $structure) above
1322 $struct = ltrim($struct, '/');
1324 //replace tags with regexes
1325 $match = str_replace($this->rewritecode, $this->rewritereplace, $struct);
1327 //make a list of tags, and store how many there are in $num_toks
1328 $num_toks = preg_match_all('/%.+?%/', $struct, $toks);
1330 //get the 'tagname=$matches[i]'
1331 $query = ( isset($queries) && is_array($queries) && !empty($num_toks) ) ? $queries[$num_toks - 1] : '';
1333 //set up $ep_mask_specific which is used to match more specific URL types
1334 switch ( $dirs[$j] ) {
1336 $ep_mask_specific = EP_YEAR;
1339 $ep_mask_specific = EP_MONTH;
1342 $ep_mask_specific = EP_DAY;
1345 $ep_mask_specific = EP_NONE;
1348 //create query for /page/xx
1349 $pagematch = $match . $pageregex;
1350 $pagequery = $index . '?' . $query . '&paged=' . $this->preg_index($num_toks + 1);
1352 //create query for /comment-page-xx
1353 $commentmatch = $match . $commentregex;
1354 $commentquery = $index . '?' . $query . '&cpage=' . $this->preg_index($num_toks + 1);
1356 if ( get_option('page_on_front') ) {
1357 //create query for Root /comment-page-xx
1358 $rootcommentmatch = $match . $commentregex;
1359 $rootcommentquery = $index . '?' . $query . '&page_id=' . get_option('page_on_front') . '&cpage=' . $this->preg_index($num_toks + 1);
1362 //create query for /feed/(feed|atom|rss|rss2|rdf)
1363 $feedmatch = $match . $feedregex;
1364 $feedquery = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
1366 //create query for /(feed|atom|rss|rss2|rdf) (see comment near creation of $feedregex)
1367 $feedmatch2 = $match . $feedregex2;
1368 $feedquery2 = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
1370 //if asked to, turn the feed queries into comment feed ones
1371 if ( $forcomments ) {
1372 $feedquery .= '&withcomments=1';
1373 $feedquery2 .= '&withcomments=1';
1376 //start creating the array of rewrites for this dir
1378 if ( $feed ) //...adding on /feed/ regexes => queries
1379 $rewrite = array($feedmatch => $feedquery, $feedmatch2 => $feedquery2);
1380 if ( $paged ) //...and /page/xx ones
1381 $rewrite = array_merge($rewrite, array($pagematch => $pagequery));
1383 //only on pages with comments add ../comment-page-xx/
1384 if ( EP_PAGES & $ep_mask || EP_PERMALINK & $ep_mask )
1385 $rewrite = array_merge($rewrite, array($commentmatch => $commentquery));
1386 else if ( EP_ROOT & $ep_mask && get_option('page_on_front') )
1387 $rewrite = array_merge($rewrite, array($rootcommentmatch => $rootcommentquery));
1391 foreach ( (array) $ep_query_append as $regex => $ep) {
1392 //add the endpoints on if the mask fits
1393 if ( $ep[0] & $ep_mask || $ep[0] & $ep_mask_specific )
1394 $rewrite[$match . $regex] = $index . '?' . $query . $ep[1] . $this->preg_index($num_toks + 2);
1398 //if we've got some tags in this dir
1403 //check to see if this dir is permalink-level: i.e. the structure specifies an
1404 //individual post. Do this by checking it contains at least one of 1) post name,
1405 //2) post ID, 3) page name, 4) timestamp (year, month, day, hour, second and
1406 //minute all present). Set these flags now as we need them for the endpoints.
1407 if ( strpos($struct, '%postname%') !== false
1408 || strpos($struct, '%post_id%') !== false
1409 || strpos($struct, '%pagename%') !== false
1410 || (strpos($struct, '%year%') !== false && strpos($struct, '%monthnum%') !== false && strpos($struct, '%day%') !== false && strpos($struct, '%hour%') !== false && strpos($struct, '%minute%') !== false && strpos($struct, '%second%') !== false)
1413 if ( strpos($struct, '%pagename%') !== false )
1418 // For custom post types, we need to add on endpoints as well.
1419 foreach ( get_post_types( array('_builtin' => false ) ) as $ptype ) {
1420 if ( strpos($struct, "%$ptype%") !== false ) {
1422 $page = is_post_type_hierarchical( $ptype ); // This is for page style attachment url's
1428 //if we're creating rules for a permalink, do all the endpoints like attachments etc
1430 //create query and regex for trackback
1431 $trackbackmatch = $match . $trackbackregex;
1432 $trackbackquery = $trackbackindex . '?' . $query . '&tb=1';
1433 //trim slashes from the end of the regex for this dir
1434 $match = rtrim($match, '/');
1435 //get rid of brackets
1436 $submatchbase = str_replace( array('(', ')'), '', $match);
1438 //add a rule for at attachments, which take the form of <permalink>/some-text
1439 $sub1 = $submatchbase . '/([^/]+)/';
1440 $sub1tb = $sub1 . $trackbackregex; //add trackback regex <permalink>/trackback/...
1441 $sub1feed = $sub1 . $feedregex; //and <permalink>/feed/(atom|...)
1442 $sub1feed2 = $sub1 . $feedregex2; //and <permalink>/(feed|atom...)
1443 $sub1comment = $sub1 . $commentregex; //and <permalink>/comment-page-xx
1445 //add another rule to match attachments in the explicit form:
1446 //<permalink>/attachment/some-text
1447 $sub2 = $submatchbase . '/attachment/([^/]+)/';
1448 $sub2tb = $sub2 . $trackbackregex; //and add trackbacks <permalink>/attachment/trackback
1449 $sub2feed = $sub2 . $feedregex; //feeds, <permalink>/attachment/feed/(atom|...)
1450 $sub2feed2 = $sub2 . $feedregex2; //and feeds again on to this <permalink>/attachment/(feed|atom...)
1451 $sub2comment = $sub2 . $commentregex; //and <permalink>/comment-page-xx
1453 //create queries for these extra tag-ons we've just dealt with
1454 $subquery = $index . '?attachment=' . $this->preg_index(1);
1455 $subtbquery = $subquery . '&tb=1';
1456 $subfeedquery = $subquery . '&feed=' . $this->preg_index(2);
1457 $subcommentquery = $subquery . '&cpage=' . $this->preg_index(2);
1459 //do endpoints for attachments
1460 if ( !empty($endpoints) ) {
1461 foreach ( (array) $ep_query_append as $regex => $ep ) {
1462 if ( $ep[0] & EP_ATTACHMENT ) {
1463 $rewrite[$sub1 . $regex] = $subquery . $ep[1] . $this->preg_index(3);
1464 $rewrite[$sub2 . $regex] = $subquery . $ep[1] . $this->preg_index(3);
1469 //now we've finished with endpoints, finish off the $sub1 and $sub2 matches
1470 //add a ? as we don't have to match that last slash, and finally a $ so we
1471 //match to the end of the URL
1475 //post pagination, e.g. <permalink>/2/
1476 $match = $match . '(/[0-9]+)?/?$';
1477 $query = $index . '?' . $query . '&page=' . $this->preg_index($num_toks + 1);
1478 } else { //not matching a permalink so this is a lot simpler
1479 //close the match and finalise the query
1481 $query = $index . '?' . $query;
1484 //create the final array for this dir by joining the $rewrite array (which currently
1485 //only contains rules/queries for trackback, pages etc) to the main regex/query for
1487 $rewrite = array_merge($rewrite, array($match => $query));
1489 //if we're matching a permalink, add those extras (attachments etc) on
1492 $rewrite = array_merge(array($trackbackmatch => $trackbackquery), $rewrite);
1494 //add regexes/queries for attachments, attachment trackbacks and so on
1495 if ( ! $page ) //require <permalink>/attachment/stuff form for pages because of confusion with subpages
1496 $rewrite = array_merge($rewrite, array($sub1 => $subquery, $sub1tb => $subtbquery, $sub1feed => $subfeedquery, $sub1feed2 => $subfeedquery, $sub1comment => $subcommentquery));
1497 $rewrite = array_merge(array($sub2 => $subquery, $sub2tb => $subtbquery, $sub2feed => $subfeedquery, $sub2feed2 => $subfeedquery, $sub2comment => $subcommentquery), $rewrite);
1500 //add the rules for this dir to the accumulating $post_rewrite
1501 $post_rewrite = array_merge($rewrite, $post_rewrite);
1503 return $post_rewrite; //the finished rules. phew!
1507 * Generate Rewrite rules with permalink structure and walking directory only.
1509 * Shorten version of {@link WP_Rewrite::generate_rewrite_rules()} that
1510 * allows for shorter list of parameters. See the method for longer
1511 * description of what generating rewrite rules does.
1513 * @uses WP_Rewrite::generate_rewrite_rules() See for long description and rest of parameters.
1517 * @param string $permalink_structure The permalink structure to generate rules.
1518 * @param bool $walk_dirs Optional, default is false. Whether to create list of directories to walk over.
1521 public function generate_rewrite_rule($permalink_structure, $walk_dirs = false) {
1522 return $this->generate_rewrite_rules($permalink_structure, EP_NONE, false, false, false, $walk_dirs);
1526 * Construct rewrite matches and queries from permalink structure.
1528 * Runs the action 'generate_rewrite_rules' with the parameter that is an
1529 * reference to the current WP_Rewrite instance to further manipulate the
1530 * permalink structures and rewrite rules. Runs the 'rewrite_rules_array'
1531 * filter on the full rewrite rule array.
1533 * There are two ways to manipulate the rewrite rules, one by hooking into
1534 * the 'generate_rewrite_rules' action and gaining full control of the
1535 * object or just manipulating the rewrite rule array before it is passed
1536 * from the function.
1541 * @return array An associate array of matches and queries.
1543 public function rewrite_rules() {
1546 if ( empty($this->permalink_structure) )
1549 // robots.txt -only if installed at the root
1550 $home_path = parse_url( home_url() );
1551 $robots_rewrite = ( empty( $home_path['path'] ) || '/' == $home_path['path'] ) ? array( 'robots\.txt$' => $this->index . '?robots=1' ) : array();
1553 // Old feed and service files
1554 $deprecated_files = array(
1555 '.*wp-(atom|rdf|rss|rss2|feed|commentsrss2)\.php$' => $this->index . '?feed=old',
1556 '.*wp-app\.php(/.*)?$' => $this->index . '?error=403',
1559 // Registration rules
1560 $registration_pages = array();
1561 if ( is_multisite() && is_main_site() ) {
1562 $registration_pages['.*wp-signup.php$'] = $this->index . '?signup=true';
1563 $registration_pages['.*wp-activate.php$'] = $this->index . '?activate=true';
1565 $registration_pages['.*wp-register.php$'] = $this->index . '?register=true'; // Deprecated
1567 // Post rewrite rules.
1568 $post_rewrite = $this->generate_rewrite_rules( $this->permalink_structure, EP_PERMALINK );
1571 * Filter rewrite rules used for "post" archives.
1575 * @param array $post_rewrite The rewrite rules for posts.
1577 $post_rewrite = apply_filters( 'post_rewrite_rules', $post_rewrite );
1579 // Date rewrite rules.
1580 $date_rewrite = $this->generate_rewrite_rules($this->get_date_permastruct(), EP_DATE);
1583 * Filter rewrite rules used for date archives.
1585 * Likely date archives would include /yyyy/, /yyyy/mm/, and /yyyy/mm/dd/.
1589 * @param array $date_rewrite The rewrite rules for date archives.
1591 $date_rewrite = apply_filters( 'date_rewrite_rules', $date_rewrite );
1593 // Root-level rewrite rules.
1594 $root_rewrite = $this->generate_rewrite_rules($this->root . '/', EP_ROOT);
1597 * Filter rewrite rules used for root-level archives.
1599 * Likely root-level archives would include pagination rules for the homepage
1600 * as well as site-wide post feeds (e.g. /feed/, and /feed/atom/).
1604 * @param array $root_rewrite The root-level rewrite rules.
1606 $root_rewrite = apply_filters( 'root_rewrite_rules', $root_rewrite );
1608 // Comments rewrite rules.
1609 $comments_rewrite = $this->generate_rewrite_rules($this->root . $this->comments_base, EP_COMMENTS, false, true, true, false);
1612 * Filter rewrite rules used for comment feed archives.
1614 * Likely comments feed archives include /comments/feed/, and /comments/feed/atom/.
1618 * @param array $comments_rewrite The rewrite rules for the site-wide comments feeds.
1620 $comments_rewrite = apply_filters( 'comments_rewrite_rules', $comments_rewrite );
1622 // Search rewrite rules.
1623 $search_structure = $this->get_search_permastruct();
1624 $search_rewrite = $this->generate_rewrite_rules($search_structure, EP_SEARCH);
1627 * Filter rewrite rules used for search archives.
1629 * Likely search-related archives include /search/search+query/ as well as
1630 * pagination and feed paths for a search.
1634 * @param array $search_rewrite The rewrite rules for search queries.
1636 $search_rewrite = apply_filters( 'search_rewrite_rules', $search_rewrite );
1638 // Author rewrite rules.
1639 $author_rewrite = $this->generate_rewrite_rules($this->get_author_permastruct(), EP_AUTHORS);
1642 * Filter rewrite rules used for author archives.
1644 * Likely author archives would include /author/author-name/, as well as
1645 * pagination and feed paths for author archives.
1649 * @param array $author_rewrite The rewrite rules for author archives.
1651 $author_rewrite = apply_filters( 'author_rewrite_rules', $author_rewrite );
1653 // Pages rewrite rules.
1654 $page_rewrite = $this->page_rewrite_rules();
1657 * Filter rewrite rules used for "page" post type archives.
1661 * @param array $page_rewrite The rewrite rules for the "page" post type.
1663 $page_rewrite = apply_filters( 'page_rewrite_rules', $page_rewrite );
1665 // Extra permastructs.
1666 foreach ( $this->extra_permastructs as $permastructname => $struct ) {
1667 if ( is_array( $struct ) ) {
1668 if ( count( $struct ) == 2 )
1669 $rules = $this->generate_rewrite_rules( $struct[0], $struct[1] );
1671 $rules = $this->generate_rewrite_rules( $struct['struct'], $struct['ep_mask'], $struct['paged'], $struct['feed'], $struct['forcomments'], $struct['walk_dirs'], $struct['endpoints'] );
1673 $rules = $this->generate_rewrite_rules( $struct );
1677 * Filter rewrite rules used for individual permastructs.
1679 * The dynamic portion of the hook name, `$permastructname`, refers
1680 * to the name of the registered permastruct, e.g. 'post_tag' (tags),
1681 * 'category' (categories), etc.
1685 * @param array $rules The rewrite rules generated for the current permastruct.
1687 $rules = apply_filters( $permastructname . '_rewrite_rules', $rules );
1688 if ( 'post_tag' == $permastructname ) {
1691 * Filter rewrite rules used specifically for Tags.
1694 * @deprecated 3.1.0 Use 'post_tag_rewrite_rules' instead
1696 * @param array $rules The rewrite rules generated for tags.
1698 $rules = apply_filters( 'tag_rewrite_rules', $rules );
1701 $this->extra_rules_top = array_merge($this->extra_rules_top, $rules);
1704 // Put them together.
1705 if ( $this->use_verbose_page_rules )
1706 $this->rules = array_merge($this->extra_rules_top, $robots_rewrite, $deprecated_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite, $author_rewrite, $date_rewrite, $page_rewrite, $post_rewrite, $this->extra_rules);
1708 $this->rules = array_merge($this->extra_rules_top, $robots_rewrite, $deprecated_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite, $author_rewrite, $date_rewrite, $post_rewrite, $page_rewrite, $this->extra_rules);
1711 * Fires after the rewrite rules are generated.
1715 * @param WP_Rewrite $this Current WP_Rewrite instance, passed by reference.
1717 do_action_ref_array( 'generate_rewrite_rules', array( &$this ) );
1720 * Filter the full set of generated rewrite rules.
1724 * @param array $this->rules The compiled array of rewrite rules.
1726 $this->rules = apply_filters( 'rewrite_rules_array', $this->rules );
1728 return $this->rules;
1732 * Retrieve the rewrite rules.
1734 * The difference between this method and {@link
1735 * WP_Rewrite::rewrite_rules()} is that this method stores the rewrite rules
1736 * in the 'rewrite_rules' option and retrieves it. This prevents having to
1737 * process all of the permalinks to get the rewrite rules in the form of
1743 * @return array Rewrite rules.
1745 public function wp_rewrite_rules() {
1746 $this->rules = get_option('rewrite_rules');
1747 if ( empty($this->rules) ) {
1748 $this->matches = 'matches';
1749 $this->rewrite_rules();
1750 update_option('rewrite_rules', $this->rules);
1753 return $this->rules;
1757 * Retrieve mod_rewrite formatted rewrite rules to write to .htaccess.
1759 * Does not actually write to the .htaccess file, but creates the rules for
1760 * the process that will.
1762 * Will add the non_wp_rules property rules to the .htaccess file before
1763 * the WordPress rewrite rules one.
1770 public function mod_rewrite_rules() {
1771 if ( ! $this->using_permalinks() )
1774 $site_root = parse_url( site_url() );
1775 if ( isset( $site_root['path'] ) )
1776 $site_root = trailingslashit($site_root['path']);
1778 $home_root = parse_url(home_url());
1779 if ( isset( $home_root['path'] ) )
1780 $home_root = trailingslashit($home_root['path']);
1784 $rules = "<IfModule mod_rewrite.c>\n";
1785 $rules .= "RewriteEngine On\n";
1786 $rules .= "RewriteBase $home_root\n";
1787 $rules .= "RewriteRule ^index\.php$ - [L]\n"; // Prevent -f checks on index.php.
1789 //add in the rules that don't redirect to WP's index.php (and thus shouldn't be handled by WP at all)
1790 foreach ( (array) $this->non_wp_rules as $match => $query) {
1791 // Apache 1.3 does not support the reluctant (non-greedy) modifier.
1792 $match = str_replace('.+?', '.+', $match);
1794 // If the match is unanchored and greedy, prepend rewrite conditions
1795 // to avoid infinite redirects and eclipsing of real files.
1796 //if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) {
1800 $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
1803 if ( $this->use_verbose_rules ) {
1804 $this->matches = '';
1805 $rewrite = $this->rewrite_rules();
1806 $num_rules = count($rewrite);
1807 $rules .= "RewriteCond %{REQUEST_FILENAME} -f [OR]\n" .
1808 "RewriteCond %{REQUEST_FILENAME} -d\n" .
1809 "RewriteRule ^.*$ - [S=$num_rules]\n";
1811 foreach ( (array) $rewrite as $match => $query) {
1812 // Apache 1.3 does not support the reluctant (non-greedy) modifier.
1813 $match = str_replace('.+?', '.+', $match);
1815 // If the match is unanchored and greedy, prepend rewrite conditions
1816 // to avoid infinite redirects and eclipsing of real files.
1817 //if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) {
1821 if ( strpos($query, $this->index) !== false )
1822 $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
1824 $rules .= 'RewriteRule ^' . $match . ' ' . $site_root . $query . " [QSA,L]\n";
1827 $rules .= "RewriteCond %{REQUEST_FILENAME} !-f\n" .
1828 "RewriteCond %{REQUEST_FILENAME} !-d\n" .
1829 "RewriteRule . {$home_root}{$this->index} [L]\n";
1832 $rules .= "</IfModule>\n";
1836 * Filter the list of rewrite rules formatted for output to an .htaccess file.
1840 * @param string $rules mod_rewrite Rewrite rules formatted for .htaccess.
1842 $rules = apply_filters( 'mod_rewrite_rules', $rules );
1845 * Filter the list of rewrite rules formatted for output to an .htaccess file.
1848 * @deprecated 1.5.0 Use the mod_rewrite_rules filter instead.
1850 * @param string $rules mod_rewrite Rewrite rules formatted for .htaccess.
1852 $rules = apply_filters( 'rewrite_rules', $rules ); // Deprecated
1858 * Retrieve IIS7 URL Rewrite formatted rewrite rules to write to web.config file.
1860 * Does not actually write to the web.config file, but creates the rules for
1861 * the process that will.
1868 public function iis7_url_rewrite_rules( $add_parent_tags = false ) {
1870 if ( ! $this->using_permalinks() )
1873 if ( $add_parent_tags ) {
1874 $rules .= '<configuration>
1881 <rule name="wordpress" patternSyntax="Wildcard">
1884 <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
1885 <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
1887 <action type="Rewrite" url="index.php" />
1890 if ( $add_parent_tags ) {
1899 * Filter the list of rewrite rules formatted for output to a web.config.
1903 * @param string $rules Rewrite rules formatted for IIS web.config.
1905 $rules = apply_filters( 'iis7_url_rewrite_rules', $rules );
1911 * Add a straight rewrite rule.
1913 * Any value in the $after parameter that isn't 'bottom' will be placed at
1914 * the top of the rules.
1919 * @param string $regex Regular expression to match against request.
1920 * @param string $redirect URL regex redirects to when regex matches request.
1921 * @param string $after Optional, default is bottom. Location to place rule.
1923 public function add_rule($regex, $redirect, $after = 'bottom') {
1924 //get everything up to the first ?
1925 $index = (strpos($redirect, '?') == false ? strlen($redirect) : strpos($redirect, '?'));
1926 $front = substr($redirect, 0, $index);
1927 if ( $front != $this->index ) { //it doesn't redirect to WP's index.php
1928 $this->add_external_rule($regex, $redirect);
1930 if ( 'bottom' == $after)
1931 $this->extra_rules = array_merge($this->extra_rules, array($regex => $redirect));
1933 $this->extra_rules_top = array_merge($this->extra_rules_top, array($regex => $redirect));
1934 //$this->extra_rules[$regex] = $redirect;
1939 * Add a rule that doesn't redirect to index.php.
1941 * Can redirect to any place.
1946 * @param string $regex Regular expression to match against request.
1947 * @param string $redirect URL regex redirects to when regex matches request.
1949 public function add_external_rule($regex, $redirect) {
1950 $this->non_wp_rules[$regex] = $redirect;
1954 * Add an endpoint, like /trackback/.
1957 * @since 3.9.0 $query_var parameter added.
1960 * @see add_rewrite_endpoint() for full documentation.
1961 * @uses WP::add_query_var()
1963 * @param string $name Name of the endpoint.
1964 * @param int $places Endpoint mask describing the places the endpoint should be added.
1965 * @param string $query_var Name of the corresponding query variable. Default is value of $name.
1967 public function add_endpoint( $name, $places, $query_var = null ) {
1969 if ( null === $query_var ) {
1972 $this->endpoints[] = array( $places, $name, $query_var );
1973 $wp->add_query_var( $query_var );
1977 * Add a new permalink structure.
1979 * A permalink structure (permastruct) is an abstract definition of a set of rewrite rules; it
1980 * is an easy way of expressing a set of regular expressions that rewrite to a set of query strings.
1981 * The new permastruct is added to the {@link WP_Rewrite::$extra_permastructs} array. When the
1982 * rewrite rules are built by {@link WP_Rewrite::rewrite_rules()} all of these extra permastructs
1983 * are passed to {@link WP_Rewrite::generate_rewrite_rules()} which transforms them into the
1984 * regular expressions that many love to hate.
1986 * The $args parameter gives you control over how {@link WP_Rewrite::generate_rewrite_rules()}
1987 * works on the new permastruct.
1992 * @param string $name Name for permalink structure.
1993 * @param string $struct Permalink structure (e.g. category/%category%)
1994 * @param array $args Optional configuration for building the rules from the permalink structure:
1995 * - with_front (bool) - Should the structure be prepended with WP_Rewrite::$front? Default is true.
1996 * - ep_mask (int) - Endpoint mask defining what endpoints are added to the structure. Default is EP_NONE.
1997 * - paged (bool) - Should archive pagination rules be added for the structure? Default is true.
1998 * - feed (bool) - Should feed rewrite rules be added for the structure? Default is true.
1999 * - forcomments (bool) - Should the feed rules be a query for a comments feed? Default is false.
2000 * - walk_dirs (bool) - Should the 'directories' making up the structure be walked over and rewrite
2001 * rules built for each in turn? Default is true.
2002 * - endpoints (bool) - Should endpoints be applied to the generated rewrite rules? Default is true.
2004 public function add_permastruct( $name, $struct, $args = array() ) {
2005 // backwards compatibility for the old parameters: $with_front and $ep_mask
2006 if ( ! is_array( $args ) )
2007 $args = array( 'with_front' => $args );
2008 if ( func_num_args() == 4 )
2009 $args['ep_mask'] = func_get_arg( 3 );
2012 'with_front' => true,
2013 'ep_mask' => EP_NONE,
2016 'forcomments' => false,
2017 'walk_dirs' => true,
2018 'endpoints' => true,
2020 $args = array_intersect_key( $args, $defaults );
2021 $args = wp_parse_args( $args, $defaults );
2023 if ( $args['with_front'] )
2024 $struct = $this->front . $struct;
2026 $struct = $this->root . $struct;
2027 $args['struct'] = $struct;
2029 $this->extra_permastructs[ $name ] = $args;
2033 * Remove rewrite rules and then recreate rewrite rules.
2035 * Calls {@link WP_Rewrite::wp_rewrite_rules()} after removing the
2036 * 'rewrite_rules' option. If the function named 'save_mod_rewrite_rules'
2037 * exists, it will be called.
2041 * @param bool $hard Whether to update .htaccess (hard flush) or just update rewrite_rules option (soft flush). Default is true (hard).
2043 public function flush_rules($hard = true) {
2044 delete_option('rewrite_rules');
2045 $this->wp_rewrite_rules();
2047 * Filter whether a "hard" rewrite rule flush should be performed when requested.
2049 * A "hard" flush updates .htaccess (Apache) or web.config (IIS).
2053 * @param bool $hard Whether to flush rewrite rules "hard". Default true.
2055 if ( ! $hard || ! apply_filters( 'flush_rewrite_rules_hard', true ) ) {
2058 if ( function_exists( 'save_mod_rewrite_rules' ) )
2059 save_mod_rewrite_rules();
2060 if ( function_exists( 'iis7_save_url_rewrite_rules' ) )
2061 iis7_save_url_rewrite_rules();
2065 * Sets up the object's properties.
2067 * The 'use_verbose_page_rules' object property will be set to true if the
2068 * permalink structure begins with one of the following: '%postname%', '%category%',
2069 * '%tag%', or '%author%'.
2074 public function init() {
2075 $this->extra_rules = $this->non_wp_rules = $this->endpoints = array();
2076 $this->permalink_structure = get_option('permalink_structure');
2077 $this->front = substr($this->permalink_structure, 0, strpos($this->permalink_structure, '%'));
2079 if ( $this->using_index_permalinks() )
2080 $this->root = $this->index . '/';
2081 unset($this->author_structure);
2082 unset($this->date_structure);
2083 unset($this->page_structure);
2084 unset($this->search_structure);
2085 unset($this->feed_structure);
2086 unset($this->comment_feed_structure);
2087 $this->use_trailing_slashes = ( '/' == substr($this->permalink_structure, -1, 1) );
2089 // Enable generic rules for pages if permalink structure doesn't begin with a wildcard.
2090 if ( preg_match("/^[^%]*%(?:postname|category|tag|author)%/", $this->permalink_structure) )
2091 $this->use_verbose_page_rules = true;
2093 $this->use_verbose_page_rules = false;
2097 * Set the main permalink structure for the blog.
2099 * Will update the 'permalink_structure' option, if there is a difference
2100 * between the current permalink structure and the parameter value. Calls
2101 * {@link WP_Rewrite::init()} after the option is updated.
2103 * Fires the 'permalink_structure_changed' action once the init call has
2104 * processed passing the old and new values
2109 * @param string $permalink_structure Permalink structure.
2111 public function set_permalink_structure($permalink_structure) {
2112 if ( $permalink_structure != $this->permalink_structure ) {
2113 $old_permalink_structure = $this->permalink_structure;
2114 update_option('permalink_structure', $permalink_structure);
2118 * Fires after the permalink structure is updated.
2122 * @param string $old_permalink_structure The previous permalink structure.
2123 * @param string $permalink_structure The new permalink structure.
2125 do_action( 'permalink_structure_changed', $old_permalink_structure, $permalink_structure );
2130 * Set the category base for the category permalink.
2132 * Will update the 'category_base' option, if there is a difference between
2133 * the current category base and the parameter value. Calls
2134 * {@link WP_Rewrite::init()} after the option is updated.
2139 * @param string $category_base Category permalink structure base.
2141 public function set_category_base($category_base) {
2142 if ( $category_base != get_option('category_base') ) {
2143 update_option('category_base', $category_base);
2149 * Set the tag base for the tag permalink.
2151 * Will update the 'tag_base' option, if there is a difference between the
2152 * current tag base and the parameter value. Calls
2153 * {@link WP_Rewrite::init()} after the option is updated.
2158 * @param string $tag_base Tag permalink structure base.
2160 public function set_tag_base( $tag_base ) {
2161 if ( $tag_base != get_option( 'tag_base') ) {
2162 update_option( 'tag_base', $tag_base );
2168 * Constructor - Calls init(), which runs setup.
2173 * @return WP_Rewrite
2175 public function __construct() {