Michael Giovanni Pumo Michael Giovanni Pumo - 1 year ago 70
PHP Question

WordPress - Cannot get add_rewrite_rule() to work

I'm trying to get a rewrite rule going on a page in my WordPress website.

I have a page called latest, with a custom template and it has an ID of 10.

At the moment, I am making several dynamic requests based on the query string like so:


What I would like instead is:


Here's what I've tried so far.


function custom_rewrite_tag() {
add_rewrite_tag('%type%', '([^&]+)');

add_action('init', 'custom_rewrite_tag', 10, 0);

function custom_rewrite_rule() {
add_rewrite_rule('^latest/([^/]*)/([^/]*)/?','index.php?page_id=10&type=$matches[1]', 'top');

add_action('init', 'custom_rewrite_rule', 10, 0);

I was following the guide found here:

For the life of me, I cannot get this to work. It simply forwards to my 404 page or tries to find a post that has a title sort of matching the type parameter and redirects me.

Any clues as to what I'm doing wrong? I have refreshed the permalinks too.

Answer Source

It turns out, I have an extra path in the rewrite rule.

Instead of: '^latest/([^/]*)/([^/]*)/?' it should have been: '^latest/([^/]*)/?'

My new working function in functions.php is as follows:

function custom_rewrite_rule() {
    add_rewrite_tag('%type%', '([^&]+)');
    add_rewrite_rule('^latest/([^/]*)/?', 'index.php?page_id=10&type=$matches[1]', 'top' );

add_action('init', 'custom_rewrite_rule', 10, 1);

Hope this helps someone in future!