Creating a Custom PDF Viewer Shortcode in WordPress

Photo by CURVD® on Unsplash

Creating a Custom PDF Viewer Shortcode in WordPress

With the WordPress Snippets Plugin

Hello there, WordPress enthusiasts! Today, we're going to walk through a handy WordPress solution that will allow you to display PDF files directly on your posts or pages using a custom shortcode.

In a nutshell, we're building a custom WordPress script that will create a shortcode accepting a PDF file (from your WordPress Media Library) as an argument, along with optional width and height parameters. And if the content of the PDF exceeds its container size, a scrollbar will be added for easy navigation.

<?php
/*
Plugin Name: My PDF Shortcode
Description: A plugin that adds a PDF viewer shortcode.
Version: 1.2
Author: Theo van der Sluijs
*/

function my_pdf_shortcode($atts) {
    $a = shortcode_atts( array(
        'id' => '',
        'width' => '100%',  // default width
        'height' => '141.4%' // default height (A4 ratio)
    ), $atts );

    $pdf_url = wp_get_attachment_url($a['id']);

    if($pdf_url) {
        $output = '<div style="width: '.$a['width'].'; overflow: auto; position: relative; padding-top: '.$a['height'].'">
                    <object data="' . $pdf_url . '" type="application/pdf" style="position: absolute; top: 0; left: 0; height: 100%; width: 100%;">
                        <p>It appears you don\'t have a PDF plugin for this browser. No biggie... you can <a href="'.$pdf_url.'">click here to download the PDF file.</a></p>
                    </object>
                   </div>';
    } else {
        $output = '<p>No PDF found!</p>';
    }

    return $output;
}
add_shortcode('my_pdf', 'my_pdf_shortcode');

Let's delve into the code.

<?php
/*
Plugin Name: My PDF Shortcode
Description: A plugin that adds a PDF viewer shortcode.
Version: 1.2
Author: Your Name
*/

function my_pdf_shortcode($atts) {
    //...
}
add_shortcode('my_pdf', 'my_pdf_shortcode');

The code above introduces our plugin and declares a function called my_pdf_shortcode(). This function is registered as a shortcode via the add_shortcode() function.

Let's inspect the inside of the my_pdf_shortcode() function.

$a = shortcode_atts( array(
    'id' => '',
    'width' => '100%',  // default width
    'height' => '141.4%' // default height (A4 ratio)
), $atts );

This code block defines the attributes our shortcode will accept: 'id', 'width', and 'height'. The 'id' is a required attribute for the PDF from your Media Library, whereas 'width' and 'height' are optional.

$pdf_url = wp_get_attachment_url($a['id']);

Here we fetch the URL of the PDF using WordPress's wp_get_attachment_url() function and the id provided.

if($pdf_url) {
    //...
} else {
    $output = '<p>No PDF found!</p>';
}

In the 'if' block, we check if the PDF URL is successfully retrieved. If it fails (maybe the 'id' is wrong or the PDF doesn't exist), we display a message saying "No PDF found!"

Now, let's look inside the 'if' block.

$output = '<div style="width: '.$a['width'].'; overflow: auto; position: relative; padding-top: '.$a['height'].'">
                <object data="' . $pdf_url . '" type="application/pdf" style="position: absolute; top: 0; left: 0; height: 100%; width: 100%;">
                    <p>It appears you don\'t have a PDF plugin for this browser. No biggie... you can <a href="'.$pdf_url.'">click here to download the PDF file.</a></p>
                </object>
            </div>';

This is where the magic happens. We create an HTML 'div' that houses an 'object' element (for the PDF). The 'div' has a CSS style applied to it that manages the width, height, position, and overflow behavior. 'Overflow: auto;' ensures that scrollbars appear when the PDF content exceeds its container size.

Inside the 'object' tag, we set the 'data' attribute to the URL of our PDF file. In case the browser doesn't support PDF viewing, we include a link to download the PDF.

In the end, our function returns the output string, which will be displayed wherever we use our shortcode.

With this custom plugin, you can easily insert any PDF from your Media Library to your WordPress posts or pages with a simple shortcode like this: [my_pdf id="123" width="50%" height="70.7%"].

That's it! You've now got a custom WordPress plugin that creates a PDF viewer shortcode. This simple, yet powerful solution can be a real game-changer for anyone who frequently shares PDF content on their WordPress site. Enjoy!

Did you find this article valuable?

Support Theo van der Sluijs by becoming a sponsor. Any amount is appreciated!