Autoswitch System: Server-Side and Client-Side implementation

Weglot uses an auto-switch mechanism to automatically redirect users to the correct language version of the site based on their browser settings .

By default, Weglot provides a server-side auto-switch feature. This works well in most cases, but sometimes it can be affected by caching systems or specific plugins that modify the request or response cycle. When that happens, the redirection may not behave as expected. To overcome these limitations, we’ve implemented a client-side auto-switch using Weglot’s JavaScript library.

  1. Disable the server-side auto-switch In your WordPress admin panel, go to Weglot → Settings and turn off the Auto-switch option.

  2. Add the following filters to your theme or custom plugin Add and activate Code Snippets plugin on your WordPress: https://wordpress.org/plugins/code-snippets/arrow-up-right In your WordPress back office, go to Snippets -> Add new Add a title (example: Weglot - Autoswitch js)

    1. Add the following code into the code input.

    2. Save changes

    function custom_weglot_dynamics_selectors( $default_dynamics ) {
        return [];
    }
    add_filter( 'weglot_dynamics_selectors', 'custom_weglot_dynamics_selectors' );
    add_filter( 'weglot_whitelist_selectors', 'custom_weglot_dynamics_selectors' );
    add_filter( 'weglot_translate_dynamics', '__return_true' );
    add_filter( 'weglot_allowed_urls', function( $urls ) {
        return 'all';
    });

    These filters ensure that Weglot’s JS library is properly loaded and ready to handle client-side switching.

  3. Add the following filter:

    add_filter( 'weglot_autoredirect_js', '__return_true' );

    Once this filter is active, you can trigger the auto-switch logic manually if needed:

    $js_autoswitch = apply_filters( 'weglot_autoredirect_js', false );

You can Also add the filter using mu-plugin or in the functions.php file in your theme With this setup, Weglot will perform the language auto-switch client-side via JavaScript, ensuring compatibility with caching systems and other plugins that may interfere with server-side redirects.

Last updated