I am working on a website that is more of a search directory and haven't been able to find a clear answer on how to automatically create pretty links from long URL's with multiple query parameters (Wordpress).
For example, if the link looks like this: website.com/search/search-results/?address=98101,+seattle,+washington&contractor=plumber&latitude=1234&longitude=9876&filter=20&order=distance
Is there a way to make it look like this: website.com/search/search-results/98101/seattle/washington/plumber/
automatically without having to go through every link and the new pretty link will show the same page as the page with all of the query parameters?
Thanks in advance, I've been trying to figure this out all day and it's not my strong point...
Really interesting and quite technical question.
I'm just pondering here. You could create a new Table (see Creating Tables with Plugins with a
requested_urlkey and ashortened_urlvalue. The whole system would be based on that approach.First we creates a custom table in the database, if it doesn’t already exist. This table will be used to store our urls.
We could then retrieve the requested url by parsing the
$_SERVER['QUERY_STRING']and verifying the url integrity through get_query_var() as it only retrieves public query variables that are recognized byWP_Query.We would then search the table for the requested url, and if it doesn't already exist, set a new key pair value.
There is no real science here, the
$shortened_urlis just a 7 bytes alpha numerical string (Why 7? Bit.ly a famous shortener is using 7 characters).Through the
template_redirecthook, we could check the shortened url against our table and redirect based on that.As we're checking for a 404 through
is_404()first (pretty much limiting the number of empty request), you should also include a404.phpto your root.On the front end you can access your table through
Now, a few thing to understand before you go to production with this, even tho we're generating a pseudo random string through
random_bytes()andbase64_encode()they're not actually fully randomized, so you could end up with a problem at some point where two shortened url are the same. You could do a while loop and constantly check if that shortened url already exist before using it.You would also want to restrict the search query as much as you can to improve performance on the long term.
You might want also to add an expiry date.