Search code examples
phpwordpressdeepl

Do not translate specific elements with DeepL and DeepL WordPress plugin


I want to translate all text, except those contained inside of specific elements, for example:

Please open the page <x>Settings</x> to configure your system.

DeepL should translate everything except for items inside the <x> element. I read the doc here, https://www.deepl.com/docs-api/handling-xml/ignored-tags/ and have tried looking, but can not seem to find the proper hook to add that ignore_tags parameter.

I played around with the $this->request['ignore_tags'], for DeepLApiTranslate but I would rather not edit the plugin directly.

How should I handle this / any hook I should use?


Solution

  • WordPress DeepL plugin utilises wp_remote_* function to send requests to their APIs so you can hook into http_request_args filter to add the additional argument.

    Here is an example:

    add_filter(
            'http_request_args',
            static function ( array $parse_args, string $url ): array {
    
                $method = $parse_args['method'] ?? '';
    
                if ( $method === 'POST' && str_starts_with( $url, 'https://api.deepl.com/v2/translate' ) ) {
    
                    $body = (string) ( $parse_args['body'] ?? '' );
                    parse_str( $body, $results );
    
                    $results['ignore_tags'] = 'x';
                    $parse_args['body'] = http_build_query( $results );
                }
    
                return $parse_args;
            },
            10,
            2
        );
    

    Note that the code assumes that your site is running on PHP8 as it's using the str_starts_with to ensure that it filters the request arguments only when it is sending request to DeepL API endpoint.