wpml – fix language switcher urls

March 14, 2021

WPML is a very useful and very complex machine, and due to its complexity, at different stages of website creation, you can encounter various unexpected bugs.

I must say that the plugin team is doing a lot of work to improve the architecture of the plugin, but … It’s really incredibly complex. It affects almost any native operation of WordPress itself, and in addition to it, any of the plugins available on the site can do it, and of course, it is not possible to foresee all possible ways of interaction.

Here we will talk about the situation when you set up permalinks for some post-type using the add_rewrite_rule function. We are faced with the fact that, in general, everything is in order, but the language switch in all cases points to the current address of a single entry.

That is, if you have 2 languages ​​(English and German) on the site, and the permalink structure is set to add a language domain to the beginning of the url, then in the language switch you should have two urls: http://siteurl/custom_prefix/post_title and http://siteurl/de/custom_prefix/post_title. And you have both equal to the current locale, that is, either 2 English or 2 German ones.

We didn’t look for the root cause of this behavior, but we found a quick solution, it’s quick and it works:

add_filter( 'wpml_current_ls_language_url_endpoint', function( $url, $post_lang, $data, $current_endpoint ) {

    if ( $post_lang == 'de' && $data['code'] == 'en' ) {
        $url = str_replace( 'de/', '', $url );
    else if ( $post_lang == 'en' && $data['code'] == 'de' ) {
        $url = str_replace( '/custom_prefix', '/de/custom_prefix', $url );

    return $url;

}, 10, 4 );

As you can see from the snippet, the solution is based on the 'wpml_current_ls_language_url_endpoint' filter, it is only used for drawing the switcher, so you can easily edit the url here without fear of catching any other permalinks on the site.

Categorised in: html, wordpress