Custom Pretty URL in WordPress

This tutorial will help to create a pretty customized URL for wordpress post. ‘generate_rewrite_rules’ action is used to create a new URL format and ‘WP_Rewrite’ is WordPress class for managing the rewrite rules that allow you to use Pretty Permalinks feature.

Generate Pretty URL

add_action('admin_init', 'flush_rewrite_rules');
add_action('generate_rewrite_rules', 'custom_pretty_url_rewrite_rules');

function custom_pretty_url_rewrite_rules( $wp_rewrite )
{
	$new_rules = array(
		/** tag1, tag2 search **/		
		'find/(.+)/(.+)' => 'index.php?tag=' . $wp_rewrite->preg_index(2) . '&tag2=' .$wp_rewrite->preg_index(1),
	
		/** post_type, city taxonomy search **/
		'find/(.+)/(.+)' => 'index.php?post_type=' . $wp_rewrite->preg_index(2) . '&city=' .$wp_rewrite->preg_index(1),

		/** city location and tag using --in--keyword **/
		'find/(.+)/(.+)--in--(.+)' => 'index.php?tag=' . $wp_rewrite->preg_index(2) . '&city=' .$wp_rewrite->preg_index(1). '&location=' .$wp_rewrite->preg_index(3)
	);
	// Merge URL Rules
	$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}

Sample URL

//tag1, tag2 search
http://127.0.0.1/find/india/agriculture
//post_type, city taxonomy search 
http://127.0.0.1/find/usa/newyork
//city location and tag using --in-- keyword
http://127.0.0.1/find/newyork/colleges-in-albany

Retrieving the Value of a Pretty URL

We can now retrieve the value of rewritten query string variables using WordPress’s $wp_query variable.
Use the follow format to get the variable values

add_filter( 'query_vars','my_insert_query_vars' );
function my_insert_query_vars( $vars )
{
    array_push($vars, 'tag2');
    array_push($vars, 'city');
    array_push($vars, 'location');
    return $vars;
}
$wp_query->query_vars['tag2'];
$wp_query->query_vars['city'];
$wp_query->query_vars['location'];
'$_GET' will not work to get the variable values for pretty URL.