I have a custom page which uses a template called “Stores” http://example.com/stores/
. This page will have a list of states and/or companies as categories. For this system I have a custom post type “store” which can be assigned to a single category (either state or company),
Each store is not a specific page, but contact information which is displayed in a sort of phone-book style layout for states/companies.
The problem I have now is, how can I allow my “Stores” template accept URL requests from http://example.com/stores/california/
(without throwing 404 error)?
California
in this sense is not a page, but a query. I also do not want to manually create a page for each of these categories (As it is pulled from database, and automatic). I could use ?state=california
for this purpose, but I would like to learn the proper way to allow this URL within wordpress.
Is the correct way to edit htaccess file manually? Wouldn’t that be overwritten if you edit the permalink structure? How would I format the htaccess?
Create a Page Template
Add a new page and give it the slug
stores
Add A Public Query Variable
Add a rewrite rule
This will direct your request to your
stores
page.Within your Template
You can access your state variable as follows:
Flush your Permalinks
Visit Settings->Permalinks to flush your permalinks and add your rewrite rule to the stack.
I found the answer on WordPress’ website and have tested the solution: https://codex.wordpress.org/Rewrite_API/add_rewrite_rule#Using_Custom_Templates_with_custom_querystring
Create a Page Template
Create a page template for stores and apply it to a page.
Add a Rewrite Tag
In your functions.php add a rewrite tag, which lets WordPress know to look for the specific tag
Add a Rewrite Rule
Now to format the URL and point it to the index.php with the vars, enter the following in your functions.php. Note: You have to update the page_id to the page_id of the stores page (it’s 12 in this example).
From there you can browse to /stores/south-dakota/ and the $stores variable in your page template will be “south-dakota”.
I was also trying to do the same and finally did it in following way.
Add the following code to your functions.php inside your theme.
Inside you template, get the query variable using this
Here is working example to manage dynamic slug and assign template for it:
Manage your custom endpoint or slug dynamically or define it in file
/** Whitelist specifc query param * */
Include your custom template for that slug: