-1

I'm wondering is it possible to automatically add target=_blank to any PDF link I have on my website, so that it will convert

<a href="pdf1.pdf">link text</a>
<a href="pdf2.pdf">link text</a>

to

<a href="Pdf1.pdf" target="_blank">link text</a>
<a href="Pdf2.pdf" target="_blank">link text</a>

as this site has a lot of PDFs, and it would be easier to do this automatically rather than have to set them all one-by-one.

I have tried the Javascript solution:

$(".newWindow a[href$='pdf']").attr('target','_blank');

But am wondering is there a way to do this automatically in PHP, perhaps by adding something to Wordpress's functions file?

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
Ronan
  • 821
  • 12
  • 30
  • Possible duplicate of this: http://stackoverflow.com/questions/24428476/target-blank-in-all-link/24560618#24560618 – arielnmz Jul 21 '14 at 16:21
  • All those provide Javascript solutions, which is not the solution I have asked for. – Ronan Jul 21 '14 at 16:24
  • Not all of them, you can notice that if you actually read through the page. – arielnmz Jul 21 '14 at 16:27
  • The Find/Replace one would be useful if all the PDFs were being added at once, but they will be added intermittently. While the solution won't work as the page contains links that are non PDF links. – Ronan Jul 21 '14 at 16:28
  • 1
    It is actually the part of the search patterns that matters, you can implement that approach using any tool you want, like in Valentin Mercier's answer. – arielnmz Jul 21 '14 at 16:30

2 Answers2

1

If your .pdf links are only in your pages content. The fastest and easiest way to to do it is to replace inside your theme template file that shows your page content the following:

the_content();

by

echo str_replace('.pdf"', '.pdf" target="_blank"', get_the_content());

This will be inside the file content.phpof your theme.

Note that the function quoted above may have a parameter, (for example the_content('',FALSE,'');) you need to pass the same parameter in the get_the_content()function as well.

Valentin Mercier
  • 5,256
  • 3
  • 26
  • 50
1

Using regex, you can perform smarter replacements. This example below will work on all <a> tags with a PDF extension in the URL, even if the URL has parameters.

echo preg_replace('/((<a (?=.*\.pdf)(?!.*target="_blank").*?)>)/', '$2 target="_blank">', get_the_content());

This regex performs two lookaheads: first, to check if the URL contains a PDF extension; and second, to check if the target="_blank" attribute is not already set. If both of those requirements are satisfied, then it will append the target="_blank" attribute to the end of the tag.

Jake Bellacera
  • 884
  • 1
  • 9
  • 18