Custom Rewrite with Query vars

I have been stuck on this for hours and tried all these different methods but none seem to work. I’ve seen other threads with a similar problem but the solutions are not working for me. I’m hoping someone can help.

I have a page with a custom template using the permalink

example.com/central

This page accepts query variables eg :

example.com/central/?information=people

I’m trying to get a custom rewrite rule to work so that when people type in

example.com/central/information/people

it will display what

example.com/central/?information=people

does.

currently in my template functions.php I have

function add_query_vars_filter( $vars ){
  $vars[] = "information";
  return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

function custom_rewrite_tag() {
  add_rewrite_tag('%information%', '([^&]+)');
}
add_action('init', 'custom_rewrite_tag', 10, 0);

function custom_rewrite()
{
        add_rewrite_rule('^(.+)/information/(.+)/?$','index.php?p=64476&information=$matches[2]','top');
}
add_action('init', 'custom_rewrite');

When I visit

example.com/central/information/people 

I only get taken to

example.com/central/

My second issue is that p=64476 is hard coded, how do I get the id from $matches[1] ?

2 Answers
2

Add a rewrite endpoint instead of a rewrite rule and query var. This API function will do both of these things for you.

function wpd_add_my_endpoint(){
    add_rewrite_endpoint( 'information', EP_PAGES );
}
add_action( 'init', 'wpd_add_my_endpoint' );

Now any page can have information appended to the end, and the value will be available via get_query_var('information').

Leave a Comment