I have been developing a language plugin for wordpress which works completely. The only thing that is missing now is the url-rewriting. I have been looking at a lot of websites, sources and other questions on stackoverflow, but I can't seem to get my permalinks to work.
I have been able to add a query string variable like so:
public function append_query_string($url)
{
$args = array('lang' => $this->get_locale());
return add_query_arg($args, $url);
}
add_filter('page_link', array($this, 'append_query_string'));
add_filter('post_link', array($this, 'append_query_string'));
add_filter('the_permalink', array($this, 'append_query_string'));
This changes my links to http://www.mylink.com?lang=en_us
for example. What I want now, is to add a permastruct so that user can have pretty url's (e.g. http://www.mylink.com/en/
)
I have added the following piece of code:
public function add_query_var($vars)
{
$vars['lang'] = $this->get_locale();
return $vars;
}
add_filter('request' , array($this, 'add_query_var'), 10, 2 );
public function custom_permastruct()
{
add_permastruct('language', '%lang%', false);
}
add_action('wp_loaded', array($this, 'custom_permastruct'));
The only thing I need now is a rewrite rule, I presume, but I could be totally wrong. Anyone who knows what the best solution is for adding this permastruct?
EDIT
I have been trying to get this working for a month now and I don't seem to be able to get a grasp on permalinks, not even with all the previous answers and my own research. So that's why I'm bumping this post with a bounty yet again. What I need: I have a function (get_locale) that returns a language code. This language code should be implemented in my url as follows: "http://www.mywebsite.com/LANGUAGE_HERE/..."
I know I need to register my own permalink structure for that, but that is where everything goes wrong. What filters do I need and what should I put in my filter functions? Any help is greatly appreciated, because I'm getting pretty desperate here.
EDIT 2
So I added rewrite rules, but they don't seem to work either. I am getting a bit desperate here. Anyway, this is the code for the rewrite rules:
public function add_rewrite_rules()
{
$languages = $this->get_all_languages();
foreach($languages as $language) {
add_rewrite_rule('^' . $language->code . '/([^/]*)/?$', 'index.php?lang=$matches[1]', 'top');
}
}
add_action('init', array($this, 'add_rewrite_rules'));