I need to add some rewrite rules on my posts in order to have one or more urls for the same post. E.g /foo/post-name
and bar/post-name
should lead the same post. I'm using this function:
function addRewritePost() {
add_rewrite_rule( '^foo/([^/]+)/?', 'index.php?name=$matches[1]', 'top' );
add_rewrite_rule( '^bar/([^/]+)/?', 'index.php?name=$matches[1]', 'top' );
}
add_action('init','addRewritePost');
This code redirects from foo/post-name
to /post-name
and I don't want this kind of behaivor.
How can I solve this issue?
I need to add some rewrite rules on my posts in order to have one or more urls for the same post. E.g /foo/post-name
and bar/post-name
should lead the same post. I'm using this function:
function addRewritePost() {
add_rewrite_rule( '^foo/([^/]+)/?', 'index.php?name=$matches[1]', 'top' );
add_rewrite_rule( '^bar/([^/]+)/?', 'index.php?name=$matches[1]', 'top' );
}
add_action('init','addRewritePost');
This code redirects from foo/post-name
to /post-name
and I don't want this kind of behaivor.
How can I solve this issue?
1 Answer
Reset to default 1This would be bad practice, since WordPress already has a functionality to do this built in. Rewriting the built in functionality is never a good idea.
To achieve this the best way is to use Taxonomies.
Lets say you create two categories:
- Foo
- Bar
Now select the categories for the post in question and setup your permalinks structure to be /%category%/%postname%/
and you will get:
- foo/post-name
- bar/post-name
Hope this helps.