For the complete documentation index, see llms.txt. This page is also available as Markdown.

Advanced Woo Search X Weglot

Advanced Woo Search (aws) is a plugin to make advance search with WooCommerce. You can find the plugin here : https://wordpress.org/plugins/advanced-woo-search/

To make Advanced Woo Search return results in translated languages, reverse-translate the search terms into your original language before the search runs. The right hook (see the Advanced Woo Search hooks reference) is aws_search_terms.

use WeglotWP\Helpers\Helper_API;

add_filter( 'aws_search_terms', 'my_aws_search_terms' );
function my_aws_search_terms( $terms ) {
    $original_language = weglot_get_original_language();
    $current_language  = weglot_get_current_language();
    if ( $original_language === $current_language || ! $terms ) {
        return $terms;
    }

    $option_services = weglot_get_service( 'Option_Service_Weglot' );
    $api_key_private = $option_services->get_api_key_private();

    foreach ( $terms as $key => $term ) {
        $request_body = wp_json_encode( array(
            'l_from'      => $current_language,
            'l_to'        => $original_language,
            'request_url' => home_url( '/' ),
            'words'       => array(
                array( 'w' => $term, 't' => 1 ),
            ),
        ) );

        $url      = sprintf( '%s/translate?api_key=%s', Helper_API::get_api_url(), $api_key_private );
        $response = wp_remote_post( $url, array(
            'body'        => $request_body,
            'headers'     => array( 'Content-Type' => 'application/json' ),
            'method'      => 'POST',
            'data_format' => 'body',
        ) );

        if ( is_wp_error( $response ) ) {
            continue; // Keep the original term if the request fails.
        }

        $response_data = json_decode( wp_remote_retrieve_body( $response ), true );
        if ( isset( $response_data['to_words'][0] ) ) {
            $terms[ $key ] = $response_data['to_words'][0];
        }
    }

    return $terms;
}

Last updated