Making all PDFs Open in a New Window with jQuery

Recently I was faced with a request to make all the PDF documents in a WordPress site open in a new window. Not, to be honest, a task that requires a lot of expertise, but this particular site had hundreds of PDFs linked in widgets and pages, and some generated by plugins.

As I contemplated the work to be done, I shook my head at the task, and the sheer magnitude of the time that this would take. Then I realized that it didn’t have to be any work at all. I was already loading jQuery to run the site’s menu system, so why not put it to work in this too?

I opened the theme footer, and dumped this in a script tag:

 $(function() {
     $('a[href$=".pdf"]').each(function() {
          $(this).prop('target', '_blank');

And suddenly, my work was done, leaving me some extra time to catch up on this season’s Doctor Who.

Leave a Reply

%d bloggers like this: