DeepLcom / deepl-php

Official PHP library for the DeepL language translation API.
MIT License
202 stars 23 forks source link

When passing in WP $content variable, translate_text emits a type errror #15

Closed rguttersohn closed 1 year ago

rguttersohn commented 1 year ago

I am working on adding DeepL API to my organization's Wordpress site.

Right now, I have a hook that gets the content of blogs, pages and posts that has already been converted to HTML and translates it using the DeepL PHP library. It works great most of the time. However, whenever the post content includes content from a secondary query that retrieves featured posts, I get the following error:

 Uncaught Exception: texts parameter must be a non-empty string or array of non-empty strings 

However, when I check the type of the content variable and its length, it is confirmed to be a string. I checked the function in Translator.php to see what it's checking for and it's simply checking to see if the text argument is indeed a string AND is not empty.

Here's my code:

add_filter('the_content', function($content){
        if(in_the_loop()){
            $deepl_api_key = $_SERVER['DEEPL_API_KEY'];
            $translator = new \DeepL\Translator($deepl_api_key);
            $content_translated = $translator->translateText($content, 'EN', 'ES', ['tag_handling' => 'html'] );
            return $content_translated;
        }
        return $content;
  }, 99);
Here's the full error being emitted

Fatal error: Uncaught Exception: texts parameter must be a non-empty string or array of non-empty strings (View: /srv/www/site.com/current/web/app/themes/theme/resources/views/blocks/featured-posts.blade.php) (View: /srv/www/site.com/current/web/app/themes/theme/resources/views/blocks/featured-posts.blade.php) in /srv/www/site.com/current/vendor/deeplcom/deepl-php/src/Translator.php on line 558



I am somewhat grasping at straws for what is causing this issue and am aware this could be an issue with WP Core or our custom theme. However, I figured I might as well place the issue here in case it is a DeepL PHP library issue. 
rguttersohn commented 1 year ago

OK it was related to how WP loops over content. Issue not related to the library.