2

I am trying to use the wordpress rewrite rule to configure routing for a plugin that I am developing. I am calling the code from within a class I have created for my plugin - the code that I am using is:

function __construct() {
    add_action('init', array($this, 'category_rewrite_rule'), 10, 0);
}

function category_rewrite_rule() {
    add_rewrite_rule(
        '^products/([^/]*)/?',
        'index.php?category=$matches[1]',
        'top'
    );
}

It should take an url like domainname.com/products/garden and display /index.php?category=garden, but at the moment it displays the home page for the site. If I navigate directly to /index.php?category=garden I can see the expected page.

I know the code is running, as I have other functions within the class that work ok, also I can put die() within the rewrite function which works as expected.

I have been pressing save on the WP Settings -> Permalinks page to refresh the links every time I have changed my code.

I was thinking that it maybe an issue that I have with my local dev environment; I am working on a Mac using Laravel Valet, and I also noticed that I do not have a .htaccess file in the site root folder. I tried manually creating one (using the default WP code) but it has not helped.

EDIT: This afternoon I setup a Wordpress website using Laravel Forge and installed my plugin on that, but I am still encountering the same issue, so perhaps it is not the server environment after all :(

EDIT 2: I have setup a LAMP stack on a VM and the code works, so it is definitely something to do with using Laravel Valet/Forge (Nginx).

Is anyone able to help?

Thanks

the_peacock
  • 399
  • 2
  • 5
  • 19
  • And `__construct` is getting called where/how? Is it supposed to be a constructor method of an object? If so, which one? – 04FS Sep 29 '20 at 09:21
  • @04FS sorry, I simplified the code, but `__construct` is in a `class` that I have made for the active plugin. I know that the code is running as there are other functions within the class that work fine. I can also use `die()` within this function which works – the_peacock Sep 29 '20 at 09:25
  • Are you flushing permalinks via the admin or function call afterwards? You may need to do that when adding a new rewrite rule. – T Paone Oct 26 '20 at 19:07

1 Answers1

0

As suspected in my edits, the issue was because my local and first test server were using Laravel Valet and Laravel Forge (respectively).

I realised this was the issue as the code worked as expected when I tried using a LAMP stack on a VM.

So in the end I realised that I had to manually add the rewrite rules to my Nginx configuration to get them to work as it is not possible to use Wordpress' add_rewrite_rule function when your server is using Nginx.

the_peacock
  • 399
  • 2
  • 5
  • 19