Last updated on October 18, 2023

WPML language switcher AJAX

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Enable AJAX support in WPML language switcher.

The WPML language switcher is a useful feature for websites that are multilingual and use the WPML plugin. By default, the language switcher reloads the page when a different language is selected. However, you can enhance the user experience by implementing an AJAX-based language switcher that updates the content dynamically without reloading the page.

To achieve this functionality, you can use the following code snippet:

function wpsnippets_wpml_language_switcher_ajax() {
    wp_enqueue_script( 'wpml-language-switcher-ajax', get_stylesheet_directory_uri() . '/js/wpml-language-switcher-ajax.js', array( 'jquery' ), '1.0', true );
    wp_localize_script( 'wpml-language-switcher-ajax', 'wpml_ajax_object', array(
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'nonce' => wp_create_nonce( 'wpml_language_switcher_ajax_nonce' ),
    ) );
}
add_action( 'wp_enqueue_scripts', 'wpsnippets_wpml_language_switcher_ajax' );

function wpsnippets_wpml_language_switcher_ajax_callback() {
    check_ajax_referer( 'wpml_language_switcher_ajax_nonce', 'nonce' );

    $lang = $_POST['lang'];
    $url = apply_filters( 'wpml_permalink', get_permalink(), $lang );

    wp_send_json_success( array(
        'url' => $url,
    ) );
}
add_action( 'wp_ajax_wpml_language_switcher_ajax', 'wpsnippets_wpml_language_switcher_ajax_callback' );
add_action( 'wp_ajax_nopriv_wpml_language_switcher_ajax', 'wpsnippets_wpml_language_switcher_ajax_callback' );

This code snippet consists of two parts: the JavaScript part and the PHP part.

The JavaScript part enqueues a custom JavaScript file called wpml-language-switcher-ajax.js and localizes it with the necessary data, such as the AJAX URL and a security nonce.

The PHP part registers and enqueues the JavaScript file, and defines an AJAX callback function wpsnippets_wpml_language_switcher_ajax_callback(). This function checks the security nonce, retrieves the selected language from the AJAX request, generates the new URL for the selected language using the wpml_permalink filter, and sends a JSON response with the updated URL.

To use this code snippet, you need to create a JavaScript file named wpml-language-switcher-ajax.js in your theme’s JavaScript directory. In this file, you can write the necessary JavaScript code to handle the AJAX request and update the content dynamically.

Remember to replace get_stylesheet_directory_uri() with the appropriate path to your theme’s directory, and customize the JavaScript code in wpml-language-switcher-ajax.js to fit your specific needs.

This code snippet can be useful for websites that want to improve the user experience of their multilingual content by implementing an AJAX-based language switcher with WPML.

Examples

Example 1: Adding WPML language switcher using AJAX

This example demonstrates how to add a WPML language switcher to your WordPress site using AJAX. The code example below shows how to create a custom AJAX endpoint that retrieves the language switcher HTML and updates it dynamically on the front-end.

// Add AJAX endpoint for retrieving language switcher HTML
add_action( 'wp_ajax_wpsnippets_get_language_switcher', 'wpsnippets_get_language_switcher' );
add_action( 'wp_ajax_nopriv_wpsnippets_get_language_switcher', 'wpsnippets_get_language_switcher' );

function wpsnippets_get_language_switcher() {
    ob_start();
    do_action( 'wpml_add_language_selector' );
    $language_switcher = ob_get_clean();
    wp_send_json_success( $language_switcher );
}

In this code, we first add two AJAX actions to handle the request for retrieving the language switcher HTML. The wpsnippets_get_language_switcher function uses output buffering to capture the HTML generated by the wpml_add_language_selector action. We then send the HTML back as a JSON response using the wp_send_json_success function.

To trigger the AJAX request and update the language switcher dynamically, you can use JavaScript/jQuery code like this:

// Update language switcher using AJAX
jQuery(document).ready(function($) {
    $.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
            action: 'wpsnippets_get_language_switcher'
        },
        success: function(response) {
            $('.language-switcher-container').html(response.data);
        }
    });
});

This JavaScript code makes an AJAX request to the wpsnippets_get_language_switcher endpoint we defined earlier. The returned HTML is then inserted into the .language-switcher-container element on the page.

Example 2: Updating language switcher on language change

This example demonstrates how to update the language switcher dynamically when the user changes the language using WPML. The code example below shows how to listen for the icl_language_switched action and trigger an AJAX request to update the language switcher.

// Update language switcher on language change
add_action( 'icl_language_switched', 'wpsnippets_update_language_switcher' );

function wpsnippets_update_language_switcher() {
    ob_start();
    do_action( 'wpml_add_language_selector' );
    $language_switcher = ob_get_clean();
    wp_send_json_success( $language_switcher );
}

In this code, we hook into the icl_language_switched action, which is triggered when the user changes the language using WPML. The wpsnippets_update_language_switcher function is similar to the previous example, capturing the updated language switcher HTML and sending it back as a JSON response.

To handle the AJAX response and update the language switcher on the front-end, you can use JavaScript/jQuery code like this:

// Update language switcher on language change
jQuery(document).ready(function($) {
    $(document).on('icl_language_switched', function(event, lang) {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wpsnippets_update_language_switcher'
            },
            success: function(response) {
                $('.language-switcher-container').html(response.data);
            }
        });
    });
});

This JavaScript code listens for the icl_language_switched event triggered by WPML when the language is changed. It then makes an AJAX request to the wpsnippets_update_language_switcher endpoint to update the language switcher HTML.

Example 3: Customizing the language switcher HTML

This example demonstrates how to customize the HTML output of the WPML language switcher. The code example below shows how to use a custom callback function to modify the language switcher HTML before it is sent as a JSON response.

// Customize language switcher HTML
add_filter( 'wpml_add_language_selector', 'wpsnippets_customize_language_switcher', 10, 2 );

function wpsnippets_customize_language_switcher( $html, $args ) {
    // Modify the $html variable as needed
    $html = str_replace( 'class="language-switcher"', 'class="custom-language-switcher"', $html );

    return $html;
}

In this code, we use the wpml_add_language_selector filter to modify the language switcher HTML before it is sent as a JSON response. The wpsnippets_customize_language_switcher function receives the original HTML and the $args array as parameters. We can then modify the HTML as needed, in this case, replacing the class attribute with a custom class.

By using this filter, you can customize the language switcher HTML to match your site’s design or add additional functionality.

Note: The above code should be placed in your theme’s functions.php file or a custom plugin.

Last updated on October 18, 2023. Originally posted on November 28, 2023.

Leave a Reply

Your email address will not be published. Required fields are marked *