Vaibhav Mav Vaibhav Mav - 2 months ago 26
PHP Question

WordPress add_rewrite_rule 404 error

I am adding rewrite_rules for my custom project.

I was able to make them work till some extent, but have some difficulties.

Here's what i have tried out so far

public function add_query_vars($vars) {
$vars[] = 'gallery';
$vars[] = 'project';
$vars[] = 'palbum';
return $vars;
}
public function add_endpoint() {
add_rewrite_rule('^gallery/([^/]*)/([^/]*)?','index.php?gallery=true&project=$matches[1]&palbum=$matches[2]','top');
}


Here project is parent and palbum are all its child.

It seems to work properly at
mysite.com/gallery/my-project-name/my-album-name

(These page is to show single album)

But it gives me 404 error at
mysite.com/gallery/my-project-name

(These page is to show all albums which the project is parent of)

Any clue why?

Answer

Based on your rewrite rule, both the section used for project and palbum are required in order for the rewrite rule to apply. If you modify the rule just slightly, it will match what you are looking for:

public function add_endpoint() {
    /**
     *
     * Matches:
     * http://example.com/gallery/my-project-name/my-album-name/
     * http://example.com/gallery/my-project-name/my-album-name
     * http://example.com/gallery/my-project-name/
     * http://example.com/gallery/my-project-name
     */
    add_rewrite_rule('^gallery/([^/]+)/?(.*?)/?$','index.php?gallery=true&project=$matches[1]&palbum=$matches[2]','top');
}

Created a test to run against any other iterations you'd like to check - https://www.regex101.com/r/f54odP/1

Comments