I am trying to add a custom field to the post permalinks by using a combo of add_rewrite_tag
and applying a post_link
filter.
What I am aiming for is something like this:
http://example.com/%category%/%mycustomfield%/%postname%
I can manage to get the %mycustomfield%
as %psubject%
working by using
add_action( 'init', 'register_rewrite_tag');
function register_rewrite_tag() {
add_rewrite_tag( '%psubject%', '(.*)' );
}
However there are only a set number of %psubject%
values.
But the regex below, which I have tested on regex testers does not work and instead redirects all posts with this link structure to the homepage as home.php
, not even a 404
or index redirect.
add_rewrite_tag( '%psubject%', '(option1|option2|option3)');
However simply having the regex inputs below will work.
(option1) or (.*)
Such as
http://example.com/somecategory/option1/this-is-the-post-title
will show the correct post.
Edit: I have found even in WordPress 3.6 that this issue still occurs.
It appears that by using the regex OR
operator in the add_rewrite_tag
function only will allow the last option of the OR
statement, but not any before it.
Example:
add_rewrite_tag( '%slugname%', '(orange|apple|strawberry)');
Will only allow ‘strawberry’, despite the syntax being a standard OR
statement.
This issue does not occur in other WordPress functions such as add_rewrite_rule
.
Question: How can I tell the rewrite tag to only allow a set number of strings to be accepted for the permalink?
I don’t know what’s wrong but I can suggest:
%psubject%
rule is and if its pattern ((option1|option2|option3)
) has been added correctly.http://example.com/somecategory/option1/this-is-the-post-title
with the Inspector to see which rule matches.http://example.com/somecategory/option1/this-is-the-post-title
(when it showshome.php
) with the Debug Bar plugin and look at Query String, Matched Rewrite Rule, and Matched Rewrite Query.