Inventory_Presser_Plugin::generate_rewrite_rules( string $post_type, array $query_vars = array() )

Generate every possible combination of rewrite rules, including paging, based on post type taxonomy

Description Description

See also See also


Top ↑

Parameters Parameters

$post_type

(string) (Required) The name of a post type.

$query_vars

(array) (Optional) An array of query variables.

Default value: array()


Top ↑

Return Return

(array)


Top ↑

Source Source

File: inventory-presser.php

		protected function generate_rewrite_rules( $post_type, $query_vars = array() ) {
			global $wp_rewrite;

			if ( ! is_object( $post_type ) ) {
				$post_type = get_post_type_object( $post_type );
			}

			$rewrite_slugs = apply_filters(
				'invp_rewrite_slugs',
				array(
					$post_type->rewrite['slug'],
				)
			);

			$new_rewrite_rules = array();

			// Add taxonomy filters to the query vars array.
			$settings = INVP::settings();
			foreach ( Inventory_Presser_Taxonomies::query_vars_array() as $query_var ) {
				$is_active = $settings['taxonomies'][ $query_var ]['active'] ?? false;
				if ( $is_active ) {
					$query_vars[] = $query_var;
				}
			}

			/**
			 * Create two rules for searches across single and multiple terms
			 * and for each listings page.
			 * One rule is page one, and the second supports the paged variable.
			 */
			$maximum_simultaneous_filters = intval( apply_filters( 'invp_archive_filter_max', 5 ) );
			$query_vars_count             = min( $maximum_simultaneous_filters, count( $query_vars ) );
			for ( $i = 1; $i <= $query_vars_count;  $i++ ) {
				foreach ( $rewrite_slugs as $rewrite_slug ) {
					$new_rewrite_rule = $rewrite_slug . '/';
					$new_query_string = 'index.php?post_type=' . $post_type->name;

					// Prepend the rewrites & queries.
					for ( $n = 1; $n <= $i; $n++ ) {
						$new_rewrite_rule .= '(' . implode( '|', $query_vars ) . ')/([^\/]+?)/';
						$new_query_string .= '&' . $wp_rewrite->preg_index( $n * 2 - 1 ) . '[]=' . $wp_rewrite->preg_index( $n * 2 );
					}

					// Allow paging of filtered post type - WordPress expects 'page' in the URL but uses 'paged' in the query string so paging doesn't fit into our regex.
					$new_paged_rewrite_rule = $new_rewrite_rule . 'page/([0-9]{1,})/';
					$new_paged_query_string = $new_query_string . '&paged=' . $wp_rewrite->preg_index( $i * 2 + 1 );

					// Make the trailing backslash optional.
					$new_paged_rewrite_rule = $new_paged_rewrite_rule . '?$';
					$new_rewrite_rule       = $new_rewrite_rule . '?$';