ErnieBob ErnieBob - 7 months ago 15
PHP Question

Wordpress Custom Link

Hi I have a wordpress based website that contains movies and tv-shows. Meta datas include the year of release, e.g. Inception has 2010 as year_of_release, the key of the meta data value. I need to do something to make a custom link so that it would be like

website.com/year/2010


and it would show a custom page like
year.php
or whatever and take
2010
as a GET parameter so that I can show every movie released in 2010, or 2011 or whatever the parameter is.

Basically it would be like
website.com/category/sub-category
but I don't want it to be a category, since the year is saved as meta data and it would be wasteful to create a subcategory for every year.

Can anyone tell me a way to make a custom rewrite rule or to make a redirect rule to force a link like that to show a custom page of mine? Thanks in advance to everyone, I hope I made myself clear.

Answer

Add rewrite rule in functions.php

function year_rewrite() {
  add_rewrite_rule('^year/([0-9]+)/?', 'page-year.php?year=$matches[1]',    'top');
}
add_action('init', 'year_rewrite');

in your page-year.php create the loop to query the post by post meta year from the url parameter year.

Then go to Settings->Permalinks and just Save so WordPress will flush the new rules and it will work.