# PDF Viewer Shortcode

> Adds a [pdf_viewer] shortcode that shows a PDF from the Media Library or a URL inside the page with the browser's built-in viewer, plus a download link for phones that cannot display it inline.

- Type: PHP
- Runs: Run everywhere
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: shortcodes, pdf, embeds
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/pdf-embed-shortcode/

## Code

```php
add_action( 'init', function () {
    add_shortcode( 'pdf_viewer', function ( $atts ) {
        $atts = shortcode_atts( array( 'id' => 0, 'url' => '', 'height' => 700, 'title' => '' ), $atts, 'pdf_viewer' );
        $url  = $atts['id'] ? wp_get_attachment_url( absint( $atts['id'] ) ) : $atts['url'];
        $url  = esc_url( (string) $url, array( 'http', 'https' ) );

        if ( ! $url || 'pdf' !== strtolower( pathinfo( (string) wp_parse_url( $url, PHP_URL_PATH ), PATHINFO_EXTENSION ) ) ) {
            return '';
        }

        $title = '' !== $atts['title'] ? $atts['title'] : ( $atts['id'] ? get_the_title( absint( $atts['id'] ) ) : 'PDF document' );

        return sprintf(
            '<div class="wpide-pdf"><object data="%1$s#view=FitH" type="application/pdf" width="100%%" height="%2$d" aria-label="%3$s"><p><a href="%1$s">%4$s</a></p></object><p><a href="%1$s" download>Download %3$s (PDF)</a></p></div>',
            $url,
            max( 200, min( 2000, (int) $atts['height'] ) ),
            esc_attr( $title ),
            esc_html( 'Open ' . $title )
        );
    } );
} );
```

## Notes

Example [pdf_viewer id="123" height="800"]; PDFs from other domains may be blocked from embedding by that site.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "PDF Viewer Shortcode" 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/
