Adding target to PDF links in WordPress

A very short tutorial on how to add target to all PDF documents inserted in WordPress post.
First, We’ll assume that you have a situation that require adding specific target (let’s say target:”_blank”) to every link on PDF document in all posts or pages that have PDF document inserted in it.

Step 1:

Open functions.php in your editor.

Step 2:

At the end of the code in functions.php, just before the closing php tag (?>) insert this code:

/*adding target to pdf attachement*/

function add_target() {
?>

jQuery.noConflict();
jQuery(document).ready(function($){
$(‘.entry-content a[href$=’pdf‘]’).attr(‘target’,’_blank’); /*you can use other target attribute beside _blank*/
});

<?php
}
add_action(‘wp_footer’,’add_target’);

If your theme have different single post (page) class division (something other than “entry-content”) you can modify it.

The same thing can be done to files with other prefixes, like .doc, .xls …

P.S.

It’s highly recommended that you avoid adding snippets like this in your theme functions.php. You will lose it when you change the theme. Instead of that you can use this plugin:

Code snippets

That’s it.

Advertisements

2 thoughts on “Adding target to PDF links in WordPress

  1. Thanks for this – very helpful! Just a couple of things:

    1. I couldn’t get the code to work initially, until I realized that there are curly quotes in the text above. Once I replaced them with straight quotes, it worked perfectly.

    2. Rather than adding to functions.php file, use an awesome WordPress plugin called CODE SNIPPETS add the functionality to your website. It allows you to add functions without the need to edit that file. (Very helpful when your theme is updated, so you don’t lose your changes.)

    1. Hy,
      Thanx for comment.
      Yeah, the issue with quotes is related with new version of javascript in WordPress. I forgot to update this. Also, I fully agree with the fact that adding such snippets in functions.php isn’t god practice so I made an update to article.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s