Advertisement
dimaslanjaka

auto_add_titleAttr-Link

Mar 22nd, 2017
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.57 KB | None | 0 0
  1. //Auto Add Title links
  2.  
  3. function wpex_auto_add_link_titles( $content ) {
  4.  
  5.     // No need to do anything if there isn't any content
  6.     if ( empty( $content ) ) {
  7.         return $content;
  8.     }
  9.  
  10.     // Define links array
  11.     $links = array();
  12.     libxml_use_internal_errors(true);
  13.  
  14.     // Get page content
  15.     $html = new DomDocument;
  16.     $html->loadHTML( $content );
  17.     $html->preserveWhiteSpace = false;
  18.  
  19.     // Loop through all content links
  20.     foreach( $html->getElementsByTagName( 'a' ) as $link ) {
  21.  
  22.         // If the title attribute is already defined no need to do anything
  23.         if ( ! empty( $link->getAttribute( 'title' ) ) ) {
  24.             continue;
  25.         }
  26.  
  27.         // Get link text
  28.         $link_text = $link->textContent;
  29.  
  30.         // Save links and link text in $links array
  31.         if ( $link_text ) {
  32.             $links[$link_text] = $link->getAttribute( 'href' );
  33.         }
  34.  
  35.     }
  36.  
  37.     // Loop through links array and update post content to add link titles
  38.     if ( ! empty( $links ) ) {
  39.         foreach ( $links as $text => $link ) {
  40.             if ( $link && $text ) {
  41.                 $text    = esc_attr( $text ); // Sanitize
  42.                 $text    = ucwords( $text );  // Captilize words (looks better imo)
  43.                 $replace = $link .'" title="'. $text .'"'; // Add title to link
  44.                 $content = str_replace( $link .'"', $replace, $content ); // Replace post content
  45.             }
  46.  
  47.         }
  48.     }
  49.  
  50.     // Return post content
  51.     return $content;
  52.  
  53. }
  54. add_filter( 'the_content', 'wpex_auto_add_link_titles' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement