Keep the string prepended in request uri

2019-06-23 08:45发布

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.

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.

3条回答
啃猪蹄的小仙女
2楼-- · 2019-06-23 09:46

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..."

查看更多
可以哭但决不认输i
3楼-- · 2019-06-23 09:48

I hope you have to check your server setting if rewrite module inactive. From your server keep rewrite module active.

查看更多
ら.Afraid
4楼-- · 2019-06-23 09:51

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

查看更多
登录 后发表回答