0

I created a page template to serve information dynamically.

For url like

example.com/the-hamptons => index.php?page_id=92&filter=the-hamptons

For url like

example.com/page-that-exists <- show page

Basically, if the url points to a page that exists, show the page. If the page does not exist, pass everything after the / to the page template in variable 'filter'.

I added the following to functions.php in my child theme.

function add_query_vars($aVars) {
    $aVars[] = "filter";
    return $aVars;
}

// hook add_query_vars function into query_vars
add_filter('query_vars', 'add_query_vars');

and

function add_rewrite_rules($aRules) {
    $aNewRules = array('/([^/]+)/?$' => 'index.php?page_id=92&filter=matches[1]');
    $aRules = $aNewRules + $aRules;
    return $aRules;
}

// hook add_rewrite_rules function into rewrite_rules_array
add_filter('rewrite_rules_array', 'add_rewrite_rules');

I get a page not found when I type a url that does not exist.

If type a url that exists, it shows the correct page in that url.

Thank you for the help.

3
  • you can't do this with a rewrite rule. rules are in a hierarchy, the first rule that matches the pattern "wins". the query is then run, which is what determines if a page is a 404 or not.
    – Milo
    Commented Feb 24, 2019 at 6:22
  • @Milo if that was the case wouldn't all rewrites fail? Can I rewrite example.com/locations/the-hamptons?
    – jdias
    Commented Feb 24, 2019 at 13:20
  • rewrites work because each content type has a unique pattern- that's why categories have category in the url, and custom post types have a post type slug, it makes those rules unique. you can certainly create a more specific rule, but you can't have a general catch-all rule.
    – Milo
    Commented Feb 24, 2019 at 16:11

2 Answers 2

0

You are getting a 'page not found' because it is exactly that, not found.

What you can do is create a page, for instance, called 'locations' then set it up like this

example.com/locations/the-hamptons => index.php?page_id=[id_of_locations]&filter=the-hamptons

0

What I recommend is to don't overly complicate the things, this is somewhat a task more complicatedly to do.

WordPress will redirect all the pages that don't exist to a 404.php File.

From there, the most handy thing is to make a page that have a title saying something like: "Ups, you are lost." Then maybe give some example of pages/post/ what you want to give where the user might be interested and jump to.

Creating a page dynamically that doesn't exist doesn't sound like a good idea to me, but maybe I'm just wrong, and you have a solid reason... Just my opinion.

https://codex.wordpress.org/Creating_an_Error_404_Page

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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