# 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.

- Type: PHP
- Runs: Frontend only
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: pdf, links, new-tab
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/open-pdf-links-in-new-tab/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Open PDF Links in a New Tab" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
