Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress add_rewrite_rule Not returning $matches[] array items

I am trying to match the following url:

planets/animals-and-more/animal/human

To:

index.php?pagename=animal&animal-name=human

Where the page 'animal' has a custom page-animal.php template that pulls in the 'animal-name' query variable and spits it into an .

I have set up the rewrite tag:

function animal_custom_rewrite_tag() {
    add_rewrite_tag('%animal-name%', '([^&]+)');
}
add_action('init', 'animal_custom_rewrite_tag', 10, 0);

And the rewrite rule(s):

function add_some_rewrite_rules() {
    global $wp_rewrite;
    add_rewrite_rule('^planets/animals-and-more/animal/[a-zA-Z0-9]*$','index.php?pagename=animal&animal-name=$matches[4]','top');
    $wp_rewrite->flush_rules();
}
add_action( 'init' , 'add_custom_ncta_rewrite_rules' );

The rewrite rule works if I hard code a string in like 'animal-name=monkey', but it seems like the matches[n] array doesn't work at all.

I know this is all possible by modifying htaccess, but I need a solution for Wordpress.

Any idea why $matches[] doesn't work at all?

like image 547
Eric T Avatar asked Apr 30 '26 20:04

Eric T


1 Answers

Found it!

This article from theme.fm mentions that the matches[n] array only works for groups in the regex surrounded by parentheses. For example:

To get $matches1 to return 'human' when going to 'planets/animals-and-more/animal/human', the rewrite rule would need to look like this:

add_rewrite_rule('^planets/animals-and-more/animal/([a-zA-Z0-9-_]+)$','index.php?pagename=sponsorship&sponsorship_item=$matches[1]','top');

with () around the group you want to 'match'.

like image 190
Eric T Avatar answered May 03 '26 11:05

Eric T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!