1

I'm using rewrite rules to add an optional parameter to a page. This page uses a specific page template which handles the implementation of an external data source.

add_rewrite_rule('^page/([0-9]+)/?', 'index.php?pagename=page&id=$matches[1]', 'top');

When the page is loaded, the template loads an index from the external source or, if an id is given, a specific object.

Since I'm developing a theme and don't content manage the website, I'd like to add the rewrite rule based on the page name the template is used on. The slug could also be changed by editors down the line, that's why I want to somewhat automate this.

I know that rewrite rules are added (and flushed) best after theme activation, so I'm wondering if there is a different approach I could take to achieve this.

Edit It doesn't seem to be clear what I'm trying. I want that a page template enables a page to have a virtual path component. If the page link is /page I want to be able to open /page/1513 or /page/test and get 1513 or test as query parameter.

5
  • if customisation concerns data, it's more plugin development and not theme development. edit your question to give more details about the functionality you need.
    – Kaperto
    Commented Dec 14, 2019 at 7:25
  • I added some info, but I think the regexes show it pretty well. This is included in the theme because it is a page template. And I'm writing a theme for a customer, so I don't see a point in moving the logic to a plugin. It would be more complicated to do it with a plugin and in the end, alls APIs are available to both, plugins and themes. Commented Dec 14, 2019 at 13:23
  • may be this can help you ? wordpress.stackexchange.com/questions/352189/…
    – Kaperto
    Commented Dec 14, 2019 at 13:58
  • This would actually work. But as far as I know you're not supposed to add rewrite rules on each page load. Am I wrong with that? Commented Dec 14, 2019 at 14:13
  • you can and you must add this add_rewrite_rule on each page load but you flush the rules cache only after modifications
    – Kaperto
    Commented Dec 14, 2019 at 14:15

0

Your Answer

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