0

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.

1 Answer 1

1

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.

8
  • @chanchai118 that then redirects the 'programme' page to the homepage. Also oddly changes all the pages in wp-admin/edit.php?post_type=page to (no title). Jul 24, 2017 at 13:02
  • What is the name of your template file? Jul 24, 2017 at 13:05
  • 2
    You also need to set pagename=programme In your rule.
    – Milo
    Jul 24, 2017 at 13:18
  • Added pagename in rewrite rules. So the template file should be page-programme.tpl Jul 24, 2017 at 13:36
  • @Milo Thanks, did the trick was trying p= and the ID before. Jul 24, 2017 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.