0

I'm using ACF to make a multilingual site. My custom post URLs must work both with and without /en/ as prefix. E.g. mysite.com/posttype/any-slug/ and mysite.com/en/posttype/any-slug/ must display the same post.

I've tried using this rewrite rule in functions.php (and some variations of it), but have trouble getting it to work:

add_action('init', 'add_my_rule');

function add_my_rule() {
    add_rewrite_rule('^en\/posttype\/[.+]$','index.php?pagename=$matches[1]','top');
}

I've noticed there's other questions with similar titles, but the cases seem to be different from this one.

2
  • Just to make sure, you know that if mysite.com/posttype/any-slug/ and mysite.com/en/posttype/any-slug/ display both the same content, you expose your site to duplicate content issue (SEO related), right? Unless you 301 redirect one to the other...
    – ClemC
    Commented Aug 21, 2017 at 20:32
  • Yes, I'm changing locale based on the URL, and using ACF to display different content. Commented Aug 21, 2017 at 20:44

1 Answer 1

1

pagename assumes the page post type. You need to use the custom post type query var in your rule instead. Presumably you also want to detect that this is a request for en, you can add your own rewrite tag to store that, then add that to the rule:

add_action('init', 'add_my_rule');

function add_my_rule() {
    add_rewrite_tag('%my_language%', '([^&]+)');
    add_rewrite_rule(
        '^en/posttype/([^/]*)?/?$',
        'index.php?posttype=$matches[1]&my_language=en',
        'top'
    );
}
1
  • Yes, this did it! Didn't need the rewrite tag, since I detect the '/en/' in the URL and set the locale from that. Do you know if there's any benefits of setting it with the rewrite tag method? Commented Aug 22, 2017 at 7:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.