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.
Opens WPIDE on
Code
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 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.