Ad

Wordpress Add_rewrite_rule() Not Showing Expected Page

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

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad