Open PDF Links in a New Tab
Makes links to PDF files in your content open in a new browser tab, so visitors do not lose their place on your site.
Opens WPIDE on
Code
add_filter( 'the_content', function ( $content ) {
if ( false === stripos( $content, '.pdf' ) ) {
return $content;
}
$result = preg_replace_callback( '/<a\s[^>]*href=["\'][^"\']+\.pdf(?:[?#][^"\']*)?["\'][^>]*>/i', function ( $m ) {
if ( false !== stripos( $m[0], ' target=' ) ) {
return $m[0];
}
return substr( $m[0], 0, -1 ) . ' target="_blank" rel="noopener">';
}, $content );
return null === $result ? $content : $result;
}, 20 );
Notes
Links that already set a target are left unchanged.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.