Quick tips: Automatically adding PDF preview in WordPress


In one of ours latest project I needed to add PDF preview automatically every time when there is link to PDF file in page content.

Firstly I installed great plugin for PDF file preview. It’s allow me to generate preview window base on wordpress shortcode.

One problem left was that it won’t happen automatically. To achieve this I needed to use wordpress filter in my functions.php file.

add_filter('the_content', 'addpdfviewer', 1);
function addpdfviewer ($content)
global $post;
$pattern = "/<a(.*?)href=('|\")([^>]*).pdf('|\")(.*?)>(.*?)<\/a>/i";
$replacement = '<a$1href=$2$3.pdf$4$5>$6</a><br/>[pdfjs-viewer url=$3.pdf viewer_width=600px viewer_height=700px fullscreen=true download=true print=true openfile=false]';
$content = preg_replace($pattern, $replacement, $content);
return $content;

Basically, this filter is finding all links to pdf files in page content using regular expression and create PDF.js Viewer Shortcode. What is important, it is needed to put high filter priority to ensure that it’s processed before shortcodes.

Related articles

  • Hey dood – what is the “great plugin”? that might help 🙂

  • DerekD

    Hello Pawel,

    My name is Derek – I am a 1-guy shop in the United States.

    I’m trying to build upon your script for incorporating the pdf.js viewer into WordPress – SUCCESS! Your instructions were perfect. (here’s the link: http://www.wearesicc.com/quick-tips-automatically-adding-pdf-preview-in-wordpress/)

    But, I have a question: I’m trying to add additional parameters for the viewer – but, can’t figure out how to add them to the pattern/script.

    For example: I simply want to add: ‘pagemode=thumbs&zoom=page-fit’.

    Would you be able to give me guidance, by way of an example based on your pattern/script?

    Thank you, Pawel.