• I have an API that returns translated HTML to a desired target language. I am using the_content filter hook to pass the page’s HTML to the translation API. It’s working, but I noticed the_content is looping several times (on same pages, I noticed it is looping 9 times), which means the page content on the page is being passed to the translator every time it loops.

    Is there a way to determine if the query is on the last loop? I tried wrapping my the_content filter in a loop_end action, but I believe this is too late — maybe I am wrong.

    Here’s how the action and filter look right now.

     add_action('loop_end', function(){
        add_filter('the_content',  function ($content){
            static $i = 1;
            
            $content .= "<h2>This has looped {$i} times</h2>";
    
            $i++;
            
            return $content;
                    
        }, 99);
      }, 0);
    • This topic was modified 1 year, 10 months ago by rguttersohn.
Viewing 2 replies - 1 through 2 (of 2 total)
  • Use the ‘loop_end’ action hook to check if the current loop is the last one.

    Check out this post for example on how you can apply the hook

    Determine if Query is on last Loop

    Moderator bcworkz

    (@bcworkz)

    There are two different kinds of “loops” here. The WP_Query loop, and “the_content” filter being applied multiple times for the same post. “loop_end” is fine for the WP_Query loop, but doesn’t resolve multiple filter applications for the same post.

    While it’s common for hooks to fire multiple times for the same thing, 9 times is rather excessive. But multiple times is the issue, quantity is an added annoyance.

    AFAIK, there’s no way for a callback to know it’s on the final application of a filter. If the multiple applications are causing a resource usage issue, probably your best option is to cache the translation the first time through and get translations from the cache on subsequent calls. You can get an MD5 hash of the content and cache translations under the hash value as a key. If the key exists, use the associated cached value. If it does not exist, it’s the first time through and you need to get the translation.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Add hook on last content loop’ is closed to new replies.