Custom rewrite rules with pagination in wordpress

Sometimes we need to use $_GET params in custom pages for something like custom filter.
In my case i must create page with custom query_posts, filter this posts and glossary. In glossary links must look like site.com/glossary/a/ or site.com/glossary/b/

First we need to create page with slug 'glossary' and set permalink to Post name.
In theme directory copy page.php to page-glossary.php and put this code

print get_query_var('letter');

Now you go to /glossary/?letter=a you can see $_GET['letter'] param, but path /glossary/a/ doesn't work.
In your plugin or theme functions.php add next code:

/*
 * Generate rules with pagination.
 * Run flush_rules() if our rules are not yet included
 */
function htmlandcms_flush_rules(){
  $rules = get_option( 'rewrite_rules' );

  if ( ! isset( $rules['(glossary)/(\w*)$'] ) ) {
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
  }
}
add_action( 'wp_loaded','htmlandcms_flush_rules' );

/*
 * Adding the id var so that WP recognizes it
 */
function htmlandcms_insert_query_vars( $vars ) {
  array_push($vars, 'letter');
  return $vars;
}
add_filter( 'query_vars','htmlandcms_insert_query_vars' );

/**
 * Rewrite url rules.
 * @param $wp_rewrite
 */
function htmlandcms_rewrite_rules( $wp_rewrite ) {
  $wp_rewrite->rules = array(
    'glossary/(\w)/page/?([0-9]{1,})/?$' => $wp_rewrite->index . '?pagename=glossary&letter=' . $wp_rewrite->preg_index( 1 ) . '&paged=' . $wp_rewrite->preg_index( 2 ),
    'glossary/(\w)/?$' => $wp_rewrite->index . '?pagename=glossary&letter=' . $wp_rewrite->preg_index( 1 )

  ) + $wp_rewrite->rules;
}
add_action( 'generate_rewrite_rules', 'htmlandcms_rewrite_rules' );

Now you go to /glossary/a/ and have fun ;)
Don't forget rate this post!

Rating: 
6 out of 10 based on 17 ratings.
Tags: