Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- Plugin Name: Add target="_blank" to external links
- Description: This will filter links in posts and pages and add target="_blank" to those links
- Version: 1.0
- Author: Jan Dembowski
- Author URI: http://blog.dembowski.net/
- */
- add_filter( 'the_content' , 'mh_add_blank' );
- // add_filter( 'comment_text' , 'mh_add_blank' );
- function mh_add_blank( $content ) {
- // Regex to put all <a href="http://some-url-here/path/etc" into an array
- $mh_url_regex = "/\<a\ href\=\"(http|https)\:\/\/[a-zA-Z0-9\-\.]+[a-zA-Z]{2,3}.*\"[\ >]/";
- preg_match_all( $mh_url_regex , $content, $mh_matches );
- // Go through that array and add target="_blank" to external links
- for ( $mh_count = 0; $mh_count < count( $mh_matches[0] ); $mh_count++ )
- {
- $mh_old_url = $mh_matches[0][$mh_count];
- // $mh_new_url = str_replace( '" ' , '" target="_blank" ' , $mh_matches[0][$mh_count] );
- $mh_new_url = str_replace( '">' , '" target="_blank">' , $mh_matches[0][$mh_count] );
- // Array of destinations we don't want to apply the hack to.
- // Your home URL will get excluded but you can add to this array.
- // Partial matches work here, the more specific the better.
- $mh_ignore = array(
- home_url( '/' ),
- 'wordpress.org/'
- );
- // Make the substitution on all links except the ignore list
- if( !mh_array_find( $mh_old_url , $mh_ignore ) )
- $content = str_replace( $mh_old_url , $mh_new_url , $content );
- }
- return $content;
- }
- // Only see if the array element is contained in the string
- function mh_array_find( $needle , $haystack ) {
- if(!is_array($haystack)) return false;
- foreach ($haystack as $key=>$item) {
- // See if the item is in the needle
- if (strpos($needle, $item ) !== false) return true;
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment