I had a client recently where I had to import over 150 pages into their site in order to get the moved over to WordPress. I didn’t have access to the database as it was a proprietary CMS they were using, so I ended up having to use HTTrack to take an offsite copy of the entire site. Needless to say, I ended up writing a few tools to import everything so I wouldn’t have to do it manually. I uploaded all of the html files to the server, sideloaded all of the images, set the first attachment as the featured image, and was done in probably 1/10th of the time it would have taken to go through them all one by one and copy and paste. Then I realized that all of the attached PDF files opened in the same tab. I could handle this one of three ways:
- Find and replace in the database
- Javascript or jQuery to append the target attribute
- Use WordPress hooks and some fancy Regex
I opted for number 3, as it would be basically transparent, and wrote a quick plugin. This can easily be adapted to work with any extension of attachment. Here we go:
<?php /* Plugin Name: PDFs Open in New Tabs Description: This will filter PDF links in posts and pages and add target="_blank" to those links. Version: 1.0 Author: Brendan Carr Author URI: http://www.infinus.ca */ add_filter( 'the_content' , 'fr_add_blank' ); function fr_add_blank( $content ) { $fr_url_regex = "/<a href=[^>]+pdf+.*\"\>/"; preg_match_all( $fr_url_regex , $content, $fr_matches ); for ( $fr_count = 0; $fr_count <= count( $fr_matches[0] ); $fr_count++ ) { $fr_old_url = $fr_matches[0][$fr_count]; $fr_new_url = str_replace( '">' , '" target="_blank">' , $fr_matches[0][$fr_count] ); $content = str_replace( $fr_old_url , $fr_new_url , $content ); } return $content; } ?>