How to create SEF URL’s in WordPress

While working on one of my client’s plugin I needed to provide search engine friendly url’s for some custom functionality that was needed and existing plugin was not supporting such urls

       www.example.com/?param1=var1&param2=var2&param3=var3

but for search engine freindly url’s I want it to be like

      www.example.com/var1/var2/var3

So here I am sharing small code snippet which works perfectly for my plguin and showing nice url’s.

We need to update the theme function.php file, just add the below code in function.php file and modify variables according to your need.

<?php
add_filter('rewrite_rules_array','wp_insertRewriteRules');
add_filter('query_vars','wp_insertQueryVars');
add_filter('init','flushRules');

// Remember to flush_rules() when adding rules
function flushRules()
{
  global $wp_rewrite;
  $wp_rewrite->flush_rules();
}

// Adding a new rule
function wp_insertRewriteRules($rules)
{
  $newrules = array();
  $newrules['(mytestpage)/([a-zA-Z0-9_-]*)/([a-zA-Z0-9_-]*)$'] =
'index.php?pagename=$matches[1]&var1=$matches[2]&var2=$matches[3]';
  $allrules = $newrules + $rules;
  return $allrules;
}

// Adding the variables  so that WP recognizes it
function wp_insertQueryVars($vars)
{
 array_push($vars, 'id');
 array_push($vars, 'var1');
 array_push($vars, 'var2');
 return $vars;
}
?>

To access these variables from plugin file use following code:

 $var1 = $wp_query->query_vars['var1'];
 $var2 = $wp_query->query_vars['var2'];

Now this will solve your plugins search engine friendly issues.