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

Having a nice project to code?

pawel@polarbits.co // +48 606 115 330