jan_dembowski

target-blank.php

Mar 18th, 2014
687
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.90 KB | None | 0 0
  1. <?php
  2. /*
  3. Plugin Name: Add target="_blank" to external links
  4. Description: This will filter links in posts and pages and add target="_blank" to those links
  5. Version: 1.0
  6. Author: Jan Dembowski
  7. Author URI: http://blog.dembowski.net/
  8. */
  9.  
  10. add_filter( 'the_content' , 'mh_add_blank' );
  11. // add_filter( 'comment_text' , 'mh_add_blank' );
  12.  
  13. function mh_add_blank( $content ) {
  14.  
  15. // Regex to put all <a href="http://some-url-here/path/etc" into an array
  16. $mh_url_regex = "/\<a\ href\=\"(http|https)\:\/\/[a-zA-Z0-9\-\.]+[a-zA-Z]{2,3}.*\"[\ >]/";
  17.  
  18. preg_match_all( $mh_url_regex , $content, $mh_matches );
  19.  
  20. // Go through that array and add target="_blank" to external links
  21. for ( $mh_count = 0; $mh_count < count( $mh_matches[0] ); $mh_count++ )
  22.         {
  23.         $mh_old_url = $mh_matches[0][$mh_count];
  24.         // $mh_new_url = str_replace( '" ' , '" target="_blank" ' , $mh_matches[0][$mh_count] );
  25.         $mh_new_url = str_replace( '">' , '" target="_blank">' , $mh_matches[0][$mh_count] );
  26.  
  27.         // Array of destinations we don't want to apply the hack to.
  28.         // Your home URL will get excluded but you can add to this array.
  29.         // Partial matches work here, the more specific the better.
  30.  
  31.         $mh_ignore = array(
  32.                 home_url( '/' ),
  33.                 'wordpress.org/'
  34.                 );
  35.  
  36.         // Make the substitution on all links except the ignore list
  37.         if( !mh_array_find( $mh_old_url , $mh_ignore ) )
  38.                 $content = str_replace( $mh_old_url  , $mh_new_url , $content );
  39.         }
  40.  
  41. return $content;
  42. }
  43.  
  44. // Only see if the array element is contained in the string
  45. function mh_array_find( $needle , $haystack ) {
  46.         if(!is_array($haystack)) return false;
  47.         foreach ($haystack as $key=>$item) {
  48.                 // See if the item is in the needle
  49.                 if (strpos($needle, $item ) !== false) return true;
  50.         }
  51.         return false;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment