1

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] ?

1

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').

  • Hi Thanks for that, rewrite endpoint looks like a much better way to go. however I'm still getting a 404 error. I tried changing EP_PAGES to EP_PERMALINK but that didnt work also. Any ideas? – Ch3n May 26 '15 at 10:01
  • did you flush rewrite rules after changing them? – Milo May 26 '15 at 15:41
  • Hi, I did a flush by visiting the permalinks setting page in the back end. Is there another way to flush the rules or how can I test the end point is enabled? – Ch3n May 27 '15 at 0:57
  • how to do the appended thing??? add_query_var doesn't seem working.... – Vishal Kumar Sahu Mar 25 '17 at 4:54
1

Try this, I did a quick test and it worked for me. I created a page called central.

Don't forget to flush the rewrite rules after inserting this code.

add_filter( 'query_vars', 'query_vars' );
function query_vars( $vars )
{
    array_push($vars, 'information');
    return $vars;
}

add_action( 'rewrite_rules_array', 'rewrite_rules' );
function rewrite_rules( $rules )
{
    $newrules = array();
    $newrules[ 'central/information/people/?$' ] = 'index.php?pagename=central&information=people';

    return $newrules + $rules;
}

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.