Currently the code is on global_shutdown, eg. being executed on every page.
But due to the condition it does the query only when the current script is index.php (forumhome).
So why not execute it just for index.php and avoid the condition on all other pages?
I don't see a reason for putting the code in a global place when there is an appropriate hook forumhome_complete that has exactly the context you want