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

generate_rewrite_rules


Description Description

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

See also See also


Top ↑

Parameters Parameters

$post_type

(string) (Required)

$query_vars

(array) (Optional)

Default value: array()


Top ↑

Return Return

(void)


Top ↑

Source Source

File: inventory-presser.php

	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'],
		) );

		$taxonomies = get_object_taxonomies( $post_type->name, 'objects' );
		$new_rewrite_rules = array();

		// Add taxonomy filters to the query vars array
		foreach( $taxonomies as $taxonomy )
		{
		    $query_vars[] = $taxonomy->query_var;
		}

		// Loop over all the possible combinations of the query vars
		for( $i = 1; $i <= count( $query_vars );  $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 . '?$';

				// Add the new rewrites
				$new_rewrite_rules[$new_paged_rewrite_rule] = $new_paged_query_string;
				$new_rewrite_rules[$new_rewrite_rule]       = $new_query_string;
			}
		}
		return apply_filters( 'invp_rewrite_rules', $new_rewrite_rules );
	}