1

I have a Custom Post Type/Taxonomy that it's working fine right now.

I wrote some custom rewrite rules to create urls like:
domain.tld/postTypeName/parentTaxonomy/childTaxonomy/postSlug

function custom_rewrite_rules($rules) 
{
    $newrules = array();
    $newrules['lessons/(.+)/(.+)/(.+)/?$'] = 'index.php?lessons=$matches[3]';
    $newrules['lessons/(.+)/?$'] = 'index.php?level=$matches[1]';
    //$newrules['lessons/?$'] = 'index.php?post_type=lessons';

    return array_merge($newrules, $rules);
}
add_filter('rewrite_rules_array', 'custom_rewrite_rules');

What i'm try to do, is to create a new rule to create a url like:
domain.tld/postTypeName/parentTaxonomy/home

"home" it's not part of the custom post type or taxonomy and i want to use an already created Page (lessonhome) with a custom template for this url.

Added a Query Var:

function prefix_register_query_var($vars) 
{
  $vars[] = 'home';

  return $vars;
}
add_filter('query_vars', 'prefix_register_query_var');

Added a Template redirect and filter:

function prefix_url_rewrite_templates() 
{
  if (get_query_var('home') && is_singular('lessons')) 
  {
    add_filter('template_include', function() 
    {
      return get_template_directory() . '/custom-page-template.php';
    });
  }
}
add_action('template_redirect', 'prefix_url_rewrite_templates');

Added a new Rewrite rule:

$newrules['lessons/(.+)/home/?$'] = 'index.php?post_type=page&name=lessonhome&home=yes';

And the custom_rewrite_rules method changed to:

function custom_rewrite_rules($rules) 
{
    $newrules = array();
    $newrules['lessons/(.+)/(.+)/(.+)/?$'] = 'index.php?lessons=$matches[3]';
    $newrules['lessons/(.+)/home/?$'] = 'index.php?post_type=page&name=lessonhome&home=yes';
    $newrules['lessons/(.+)/?$'] = 'index.php?level=$matches[1]';
    //$newrules['lessons/?$'] = 'index.php?post_type=lessons';

    return array_merge($newrules, $rules);
}
add_filter('rewrite_rules_array', 'custom_rewrite_rules');

But it doesn't work - it's redirecting me to that page: domain.tld/lessonhome
What i'm doing wrong/missing here?

0

I really don't know why it's doing this redirect, but i fixed this by changing the post_type&name

$newrules['lessons/(.+)/home/?$'] = 'index.php?post_type=page&name=lessonhome&home=yes';

to page_id:

$newrules['lessons/(.+)/home/?$'] = 'index.php?page_id=24&home=yes';

or to pagename:

$newrules['lessons/(.+)/home/?$'] = 'index.php?pagename=lessonhome&home=yes';

and it's working fine!

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.