I have a custom post type “contest_recipe”. I can view contest recipe posts by year and by date with the following urls:
http://example.com/2011/?post_type=contest_recipe - shows all 2011 contest recipes
http://example.com/2011/7/?post_type=contest_recipe - shows all July 2011 contest recipes
I would like to simplify the url to
http://example.com/2011/recipes
http://example.com/2011/7/recipes
Is this possible?
I am not familiar with the rewrite rules concept. Can anyone recommend a tutorial on how to learn about this or provide an example?
I used this to enable yearly and monthly archive for custom post type. Just drop in this code into your functions.php
file.
This will add your custom rule right on the top of the Rules array. NB – WordPress uses rules array to store rewrite rules.
<?php
function wpse22992_custom_post_rewrite( $rewrite_rules ) {
$cpslug = 'contest_recipe'; // custom post type slug
// Rule to display monthly archive -> contest_recipe/2012/08/
$year_archive = array( $cpslug . '/([0-9]{4})/([0-9]{1,2})/?$' => 'index.php?year=$matches[1]&monthnum=$matches[2]&post_type=" . $cpslug );
// Rule to display yearly archive -> contest_recipe/2012/
$month_archive = array( $cpslug . "/([0-9]{4})/?$' => 'index.php?year=$matches[1]&post_type=" . $cpslug );
$rewrite_rules = $year_archive + $month_archive + $rewrite_rules;
return $rewrite_rules;
}
add_filter("rewrite_rules_array', 'wpse22992_custom_post_rewrite');
?>
Resource –
- WordPress Filter –
rewrite_rules_array
- WordPress plugin – Rewrite Rules Inspector
( Useful to generate even more combinations )