How To Create a Google Docs Shortcode for PDF Documents

Snippets by IsItWP

Are you looking for a way to create a Google Docs shortcode for PDF documents? This snippet will make the [pdf] shortcode link PDF documents to the Google Docs online viewer.


  1. All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin.
  2. Create the shortcode like this: [pdf href="http://example.com/file.pdf"]My PDF file[/pdf], using your own URL and text.
function pdflink($attr, $content) {
    if ($attr['href']) {
        return '<a class="pdf" href="http://docs.google.com/viewer?url=' . $attr['href'] . '">'.$content.'</a>';
    } else {
        $src = str_replace("=", "", $attr[0]);
        return '<a class="pdf" href="http://docs.google.com/viewer?url=' . $src . '">'.$content.'</a>';
add_shortcode('pdf', 'pdflink');

This snippet was created by Joen Asmussen.

Alternatively, you could use the following more advanced snippet. This snippet has a class attribute in the shortcode that you could use to display an icon for the file type link or to style the links with the default icon class.

Add this code to your theme’s functions.php file or in a site-specific plugin.

function wps_viewer($atts, $content = null) {
        "href" => 'http://',
        "class" => ''
    ), $atts));
    return '<a href="http://docs.google.com/viewer?url='.$href.'" class="'.$class.' icon">'.$content.'</a>';
add_shortcode("doc", "wps_viewer");

Here are some examples of using the shortcode this snippet creates.

[doc class="psd" href="http://www.example.com/file.psd"]my PSD file name[/doc]
[doc class="ai" href="http://www.example.com/file.ai"]my AI file name[/doc]
[doc class="svg" href="http://www.example.com/file.svg"]my SVG file name[/doc]

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 15 Best Content Marketing Tools and Plugins for WordPress.

Comments  Leave a Reply

  1. Documents Sample March 26, 2011 at 6:46 am

    I tried once and its working,thanks for sharing

    1. no problem, glad you like it!

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!