Jump to content

Hooking into 404


DrQuincy
 Share

Recommended Posts

How can I write a hook that happens when PW has dtermined the page is not found?

I have some pages where the page name is a unique numerical ID (also stored in a hidden field) followed by a standard slug.

E.g:

/folder/4545-foo-bar
/folder/89897-test-page

If someone enters, to use an example above, enters site.com/folder/4545 PW will send a 404. However, what I want to do in the hook it search for a page that has the unique numerical ID. If it exists, redirect to that. If it doesn't, allow the default 404 behaviour to occur.

I hope that makes sense.

Thanks!

Link to comment
Share on other sites

You may want to use path hooks for this: https://processwire.com/blog/posts/pw-3.0.173/#introducing-url-path-hooks

You can also hook into 404, but I don’t have a snippet handy right now. I’ll post one if no one beats me to it, but I think path hooks are probably the best way to do what you describe.

Another option would be URL segments. You could define a regex to only allow a single integer URL segment.

  • Like 3
Link to comment
Share on other sites

I'm don't know if I've missed something in your link but is it possible to add a path hook that runs when a page already exists in PW? This is esssential to what I want to accomplish.

Link to comment
Share on other sites

I think existing pages always have precedence over path hooks, so if a page called “/folder/4545” actually exists, no path hooks will run for such a request. But in your example, the page is actually called “/folder/4545-foo-bar”, so a path hook like this would trigger:

$this->wire()->addHook('(/.*)/([0-9]+)/?', function($event) {
    $page = $event->pages->findOne([
        'parent' => $event->arguments(1),
        'my_id_field' => $event->arguments(2)
	]);
	
    if($page->viewable())
        $this->wire()->session->redirect($page->url);
}); 

This should find any path whose last segment is an integer, try to find the page with that integer among the children of the preceding path, and redirect to it.

Normally I would test this before posting, but I’m not on a suitable machine…

Edited by Jan Romero
  • Like 1
Link to comment
Share on other sites

That is super helpful, thanks.

Quote

But in your example, the page is actually called “/folder/4545-foo-bar”, so a path hook like this would trigger

You are absolutely right there.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...