Keep the string prepended in request uri

I am building a WordPress website with two language support English and Danish.

I want to keep the language code string en for English and da for Danish prepended in request uri.

Read More

Like: (Currently this is working for me)

http://example.com/da

If i visit post or page, it should be map like this: (This is not working, getting 404)

http://example.com/da/post-name
http://example.com/da/page-name
http://example.com/da/post/is/too/long

I have also tried WordPress Rewrite API

add_rewrite_rule() (Rewrite rules currently i have)

<?php
add_action('init', function () {    
    add_rewrite_rule(
        '^(da|en)/?', //Regex
        'index.php?lang=$matches[1]', //request to
        'top' //called earlier than wordpress rules
    );
});

and also add_rewrite_tag(), but i think WordPress just provide an add_rewrite_endpoint (and i don’t need this at all).

I think it may only be possible with htaccess %{QUERY_STRING} conditions? (Don’t know)

.htaccess contents:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Edit:

I’m using WP Native Dashboard for translation on admin pages however on front i’m just using __() and _e() with .mo and .po files and its working perfectly.

P.S:
This problem is not specific to WordPress website, I also need this help with custom based websites in future. Provide me .htaccess rules/conditions if you can.

Related posts

Leave a Reply

3 comments

  1. If I were you, I would use plugin instead of implementing from zero. You can use this plugin for multilingual wp site. This plugin provides you three types of url structure;

    1. ?lang=en
    2. /en/foo/
    3. en.yoursite.com

    If you want to use for custom site, you can use following rewrite rule;

    RewriteEngine On
    RewriteBase /
    RewriteRule ^(en|da)/(.*)$ /$2?language=$1 [QSA,L]
    

    I assume, you are using language param for language

    Edit: There is some bugs on qTranslate plugin. That bugs can be solvable with additional plugin called qTranslate Slug. Do not forget to use this additional plugin, if you faced url pattern problems

  2. I deleted my answer as it seems the plugin should handle the rewritten URLs like example.com/da/post-name…

    At the moment the WP is loaded when you visit any URL and the “WP 404 error” is shown.

    EDIT 3:

    It seems like all is working as expected according to your very last comment: “Right now i’m manually inserting en/da in url…”