Search engine friendly URL for WordPress plugin

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Links

phpcamp pune 2011: A gathering of php enthusiast

Twitter

  • We are looking to hire few #WordPress developers with 1+ years of experience for our team apply now
    http://t.co/aFOdK1QY
    2012/02/20 13:05

  • http://t.co/rHQoh2GT
    2012/02/18 01:26
  • Can We Have Indian Language Website or Blog in WordPress?
    http://t.co/sNF4Fmwt
    2012/02/14 11:39
  • How to Create Your Own Super Simple #WordPress Plugins
    http://t.co/uUVEA62u
    2012/02/09 20:44
  • going to read "Internet Marketing with WordPress" over weekend, will write a review as well
    http://t.co/E0wXmXlp
    2012/02/08 16:32

Pages