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/

The first step is to find the right hook to be able to modifiy the terms search before the request is sending. According this doc : https://advanced-woo-search.com/guide/hooks-reference/ thr right hook is aws_search_terms.

And create the function to make the reverse translate

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 ) {
		return $terms;
	}
    $option_services = weglot_get_service( 'Option_Service_Weglot' );
	$api_key_private = $option_services->get_api_key_private();
	if ( $terms ) {
		foreach ($terms as $key => $term) {
			$requestBody = 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);
			$args = array(
				'body'        => $requestBody,
				'headers'     => array(
					'Content-Type' => 'application/json',
				),
				'method'      => 'POST',
				'data_format' => 'body',
			);
			$response = wp_remote_post($url, $args);
			if (is_wp_error($response)) {
				return "WP Error: " . $response->get_error_message();
			}

			// Get the response body.
			$response_body = wp_remote_retrieve_body($response);

			// Parse the JSON response.
			$responseData = json_decode($response_body, true);
			if (!$responseData || !isset($responseData['ids'])) {
				// do nothing
			}else{
                             $term = $responseData['to_words'][0];
			     $term = explode(' ', $term);
                             foreach ($term as $separate_term){
	                         $terms[$key] = $separate_term;
                             }
                       }
		}
	}
	return $terms;
}

Last updated