Reputation: 741
I can't find a real solution here about how can i make custom language permalinks in Wordpress.
For translation i use loco translater plugin (basically it's a .po,.pot file editor)
I need this structure:
domain.com/
- homepage orig language
domain.com/en/
- homepage english
domain.com/blog/
- blog post list from nl_NL category
domain.com/en/blog/
- blog post list from en_US category
domain.com/blog/this-is-a-post/
- blog post if it's in nl_NL category
domain.com/blog/en/this-is-a-post/
- blog post if it's in en_US category
.htaccess is not solution because the blog post custom permalinks
The best solution would be something like:
If there is /en/ right after the url, wordpress read permalinks after /en/, not after the url, and send a get parameter "lang=en_US"
If there isn't /en/ everything is normal.
Thank you for your help!
Peter
Upvotes: 1
Views: 2568
Reputation: 741
Finally, I figure out the solution.
function filter_post_link($permalink, $post) {
$cat_ID = get_the_category($post->ID)[0]->cat_ID;
if ($post->post_type != 'post')
return $permalink;
if($cat_ID==3){
return 'en'.$permalink;
}else{
return $permalink;
}
}
add_filter('pre_post_link', 'filter_post_link', 10, 2);
function my_add_rewrite_rules() {
global $wp,$wp_rewrite;
$wp->add_query_var('lang');
add_rewrite_rule('^en/?$', 'index.php?lang=en_US', 'top');
add_rewrite_rule('^blog/?$', 'index.php?cat=4', 'top');
add_rewrite_rule('^blog/page/([0-9]+)/?$', 'index.php?cat=4&paged=$matches[1]', 'top');
add_rewrite_rule('^en/blog/?$', 'index.php?lang=en_US&cat=3', 'top');
add_rewrite_rule('^en/blog/page/([0-9]+)/?$', 'index.php?lang=en_US&cat=3&paged=$matches[1]', 'top');
add_rewrite_rule('^en/?([^/]+)/?$', 'index.php?name=$matches[1]&lang=en_US', 'top');
// Once you get working, remove this next line
$wp_rewrite->flush_rules(false);
}
add_action('init', 'my_add_rewrite_rules');
Explanation:
I can use add_rewrite_rule()
function instead of .htaccess if i would like to use permalinks instead of plain urls.
The format of this function very similar to .htaccess, don't need more explanation.
The filter_post_link function forces /en/
part to url before post slug, IF post category id = 3.
Everything works like a charm! :)
PS: If you would like to get the values from your custom permalink, for example 'lang' parameter, you can do it this way:
$wp_query->query_vars['lang']
Upvotes: 1