I found where the problem was. The code was attached to the "the_content" hook which runs after the thumbnail is generated. 

Attached the code to "post_thumbnail_html" and it works now.