In WordPress, you can easily create a pretty URL by going to the Settings -> Permalinks section and update the permalink structure. However, if you are creating your own themes or plugins, there are times when you need to create a custom permalink structure.
For example: you want to implement a permalink: http://your-site.com/movies/1 which translates to http://your-site.com/index.php?movies=1.
Here’s how you do it:
In your plugin or theme’s functions.php file, add the following lines:
add_action('generate_rewrite_rules', 'my_add_rewrite_rules'); function my_add_rewrite_rules( $wp_rewrite ) { $new_rules = array( 'movies/(.+)' => 'index.php?movies=' . $wp_rewrite->preg_index(1) ); $wp_rewrite->rules = $new_rules + $wp_rewrite->rules; }
add_filter( 'query_vars','my_insert_query_vars' ); function my_insert_query_vars( $vars ) { array_push($vars, 'movies'); return $vars; }
add_filter('parse_query','my_parseQuery'); function my_parseQuery() { if (get_query_var('movies')) add_action('template_redirect', 'my_template'); } function my_template() { include(TEMPLATEPATH . '/movies.php'); exit; }
The first function translate the new permalink structure to the one you want.
The second function is to add the query variable into the default variable list.
The third function is to redirect the page to a custom template when the new query variable is detected.
That’s it.