I want to use custom template redirects for urls such as http://example.com/foo and http://example.com/foo/bar

I'm using add_rewrite_rule function for this

add_action('init', function() { 
  add_rewrite_rule( "^foo/([^/]*)/?", 'index.php?foo=1&bar=$matches[1]', 'top' ); 

Then I set the variables

add_filter( 'query_vars', function( $vars ){
    $vars[] = 'foo'; 
    $vars[] = 'bar';
    return $vars;

add_filter('template_include', function($original_template) {
    if(get_query_var('foo')) {
        return '/my-template.php'
    } else {
        return $original_template;

It works fine for links like http://example.com/foo/bar and in my template I can use bar variable.


But http://example.com/foo/ returns the 404 error.

Can I make this link with template redirect too?

  • I've formatted your code so it's readable, don't put everything on 1 line, it's very difficult to read! While doing that i saw one of your return statements is missing a ; – Tom J Nowell Jun 17 at 13:36
  • You are using the wrong hook. There is a difference between template_include and template_redirect. Also, you are not building the correct path for the template. – user3135691 Jun 17 at 17:07
  • @user3135691 Thank You for reply, but this code works, the template path is just an example. I thing the problem is in regexp ^foo/([^/]*)/?, so it works for urls like foo/something but not for just foo/. I was playing around this, but did not succeed – Alexey Galkevych Jun 18 at 8:42

Your Answer

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

Browse other questions tagged or ask your own question.