URL Rewrite – Page Archive

I’m trying to get a custom URL rewrite in place but having issues.

I have a page called ‘Programme’ which uses a custom query to list a post type called ‘event’. I’d like to pass a month and day variable in the url, e.g. /programme/09/31

I’ll then use the month / day variables to update the custom query. (As the events span multiple days the built in archive for ‘events’ won’t work).

Currently trying to add the rewrite results in a 404. Can I use the built in ‘m’ and ‘d’ variables, or do I need to register new URL variables?

Thanks,

Ian.

Solutions Collecting From Web of "URL Rewrite – Page Archive"

You need to add following two functions in theme functions.php or in a plugin’s php file

function func_rewrites_init(){
    add_rewrite_rule(
        'programme/(\d+)/(\d+)/?$',
        'index.php?pagename=programme&pmonth=$matches[1]&pdate=$matches[2]',
        'top' );
}
add_action('init', 'func_rewrites_init');


function func_query_vars( $query_vars ){
    $query_vars[] = 'pmonth';
    $query_vars[] = 'pdate';
    return $query_vars;
}
add_filter( 'query_vars', 'func_query_vars' );

pagename value in the above code have to be according to template name. If you have a Page with slug programme template name will be page-programme.php. In that template file you can access month and date

$pmonth = get_query_var('pmonth');
$pdate = get_query_var('pdate');

One important thing from doc:

IMPORTANT: Do not forget to flush and regenerate the rewrite rules
database after modifying rules. From WordPress Administration Screens,
Select Settings -> Permalinks and just click Save Changes without any
changes.