Using WPML with Livewire in Sage

Hi,

I have recently been trying to use Livewire inside the Sage theme.

Already got some projects running on it, also had some problems along the way, but managed to work around it.

Now I have a project which is using WPML.

I made a Livewire filter, but came across the following issue:

When filtering (Livewire updating) on a language besides the default language, the language switches back to the default language.

I’ve debugged and tried a lot of things, but the only “solution” so far is the following.

At the top of my generic filter function I do

$locale = substr(app()->getLocale(), 0, 2);
$current_locale = apply_filters( 'wpml_current_language', NULL) ?? 'nl';

if($locale != $current_locale) {
    do_action( 'wpml_switch_language', $locale );
}

It works… but its just not the perfect solution.

In Laravel, I would make a Middleware controller to check this, Sage doesn’t really “support” this yet (as far as I know).

Does anyone have a better idea / solution?

Thanks!

We had internally many headaches due to multilanguage setup with livewire. But one day as i was trying to figure out way to made it work for multisites a discovered this piece in livewire docs. Which essentially solves all the problems with content loading from wrong db/language.

In short, you just need to match your url localization with update endpoint… For example ‘/es/livewire/update’… Then it just magically works!

1 Like

I wasnt aware of this issue until now… What a shame!

Does anybody came up with a fix?

Okay found out something based on JacobBlana answer.
SImply put this into your ThemeServiceProvider Boot method.

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        // Get current language
        // This my implementation. it return the WP lang if WPML or POlylnag isnt installed, otherwise we use the plugin API to retrieve the current lang code.
        $curr_lang = Multilang::get_current_language(); /

        // Define custom Livewire update route
        Livewire::setUpdateRoute(function ($handle) use ($curr_lang) {
            return Route::post("/{$curr_lang}/livewire/update", $handle);
        });

       // Rest of your code....
}

Special thanks to Jacob for that!

1 Like

I think this is indeed the cleanest solution! :rocket:

Thanks @JacobBlana and @alexgm for your help!